Python TypeError: string indices must be integers

A common mistake for beginners is:

    extraction = mystring[1 , 10]
TypeError: string indices must be integers

The reason is because of the [1 , 10] should be changed to: [1 : 10]


This can happen when you want to extract information from a string or substring like:

mystring = 'This is a simple string [test].'
begin = mystring.find('[')
end = mystring.find(']')

if begin != -1 and end != -1:
    substr = mystring[begin, end]

The problem is that string slices with indexes has different format which is:

substr = mystring[begin: end]

and not:

substr = mystring[begin, end]


More information can be found here:

Python String Methods Tutorial

Related Article