Coding Ref

TypeError: string indices must be integers

TypeError: string indices must be integers

To solve the Python "TypeError: string indices must be integers," use an integer rather than a string as the index.

Here is an example of how the error occurs.

main.py
example_string = "Hello World"

# ⛔️ TypeError: string indices must be integers
print(example_string["ello"])

When using [] with a string, you are referencing the index of the string. An integer must be used, not a string.

For example:

main.py
example_string = "Hello World"

# ✅ We are using an integer to reference part of the string
print(example_string[1])
>> "e"

print(example_string[8])
>> "r"

print(example_string[3:8])
>> "lo Wo"

Conclusion

To solve the Python "TypeError: string indices must be integers," use an integer rather than a string as the index.

You'll also like

Related tutorials curated for you

    ModuleNotFoundError: No module named 'requests' in Python

    ModuleNotFoundError: No module named 'pip' in Python

    IndexError: list index out of range

    ValueError: setting an array element with a sequence

    How to fix: Unindent does not match any outer indentation level in Python

    ModuleNotFoundError: No module named 'pandas' in Python

    Syntax Error: invalid syntax

    TypeError: a bytes-like object is required, not 'str'

    ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

    How to fix: pandas data cast to numpy dtype of object. Check input data with np.asarray(data)

    How to fix: Can only use .str accessor with string values, which use np.object_ dtype in pandas

    Delete Conda environment