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]

Example

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]

Resources

More information can be found here:

Python String Methods Tutorial

Share Tweet Send
0 Comments
Loading...
You've successfully subscribed to SoftHints - Python, Data Science and Linux Tutorials
Great! Next, complete checkout for full access to SoftHints - Python, Data Science and Linux Tutorials
Welcome back! You've successfully signed in
Success! Your account is fully activated, you now have access to all content.