Last modified: Feb 07, 2025 By Alexander Williams

Access Characters in String by Index Python

In Python, strings are sequences of characters. You can access individual characters in a string using their index. This guide will show you how.

What is a String Index?

A string index is a position of a character in a string. In Python, indexing starts at 0. The first character has an index of 0, the second has an index of 1, and so on.

For example, in the string "Hello", the character 'H' is at index 0, 'e' at index 1, and so on.

How to Access Characters by Index

To access a character in a string, use square brackets [] with the index inside. Here's an example:


# Accessing characters by index
my_string = "Python"
first_char = my_string[0]
second_char = my_string[1]

print(first_char)  # Output: P
print(second_char) # Output: y


Output:
P
y

In this example, my_string[0] accesses the first character 'P', and my_string[1] accesses the second character 'y'.

Negative Indexing

Python also supports negative indexing. Negative indices count from the end of the string. The last character has an index of -1, the second last has -2, and so on.


# Using negative indexing
last_char = my_string[-1]
second_last_char = my_string[-2]

print(last_char)       # Output: n
print(second_last_char) # Output: o


Output:
n
o

Here, my_string[-1] accesses the last character 'n', and my_string[-2] accesses the second last character 'o'.

Common Use Cases

Accessing characters by index is useful in many scenarios. For example, you might need to check the first character of a string or extract specific parts of a string.

If you want to learn more about string manipulation, check out our guide on how to reverse a string in Python.

Handling Index Errors

If you try to access an index that doesn't exist, Python will raise an IndexError. Always ensure the index is within the string's length.


# IndexError example
try:
    print(my_string[10])
except IndexError:
    print("Index out of range")


Output:
Index out of range

In this example, my_string[10] tries to access an index that doesn't exist, causing an IndexError.

Conclusion

Accessing characters in a string by index is a fundamental skill in Python. It allows you to manipulate and analyze strings effectively. Remember, indexing starts at 0, and negative indices count from the end.

For more advanced string operations, explore our guides on multiline strings and converting integers to strings.