Skip to content Skip to sidebar Skip to footer

Another "slice Indices Must Be Integers Or None Or Have An __index__ Method" Thread

Trying to debug a Python script, and keep being this error message: Traceback (most recent call last): File '', line 3, in TypeError: slice indices

Solution 1:

You are misusing str.endswith. The second and third* parameters are start and end, which are used to index into the string, not additional strings to check for. By default these are both None, hence checking the whole string:

>>> 'foo'[None:None]
'foo'

This explains the seemingly-confusing error message; Python is trying to check filename['.jpg':None].endswith('.jpeg'), which clearly doesn't make any sense. Instead, to check for multiple strings, pass a single tuple as the first parameter:

if filename.endswith((".jpeg", ".jpg")):
                   # ^ note extra parentheses

Demo:

>>>'test.jpg'.endswith('.jpg', '.jpeg')

Traceback (most recent calllast):
  File "<pyshell#0>", line 1, in<module>'test.jpg'.endswith('.jpg', '.jpeg')
TypeError: slice indices must be integers orNoneor have an __index__ method>>>'test.jpg'.endswith(('.jpg', '.jpeg'))
True

* (or third and fourth, as instance.method(arg) can be written Class.method(instance, arg))

Post a Comment for "Another "slice Indices Must Be Integers Or None Or Have An __index__ Method" Thread"