How to access individual characters in a string in Python?

Published on Aug. 22, 2023, 12:17 p.m.

In Python, you can access individual characters in a string by specifying the string name followed by a number in square brackets. String indexing in Python is zero-based, meaning that the first character of the string has the index 0, the second character has the index 1, and so on.

Here’s an example:

my_string = "hello, world!"
first_character = my_string[0]
last_character = my_string[-1]
print(first_character)
print(last_character)

Output:

"h"
"!"

In this example, we have defined a string, and then we access the first and last characters of the string by specifying the index number in square brackets. In the case of the last character, we use a negative index to access it.

In addition to indexing, you can also use string slicing to extract a substring from a larger string. To do this, you can specify a range of index numbers separated by a colon “:” inside the square brackets.

Here’s an example:

my_string = "hello, world!"
substring = my_string[7:12]
print(substring)

Output:

"world"

In this example, we have defined a string, and then we extract a substring from the string by specifying a range of index numbers in square brackets. This returns the substring “world” starting from index 7 and up to but not including index 12.

Note that attempting to access an index outside of the range of the string will result in an IndexError.

Tags: