How to access characters of string using index in Python?
Access Characters of String using Index
To access characters of string using index, specify the index after the string variable, where the index is enclosed in opening and closing square brackets respectively.
Syntax
The syntax to access a character from string x
at index i
is
x[i]
The index starts at 0
. index is 0
for the first character, 1
for the second character, 2
for the third character and so on.
We can also provide a negative index to access a character from string. index of -1
is for the last character in the string, -2
is for the last but one character in the string, and so on.
Video Tutorial
The following video tutorial from YouTube explains how to access characters in a string with nice visuals and explanation.
Examples
1. Access character using positive index
In the following program, we take a string in name, and access the character at index 4, using square bracket notation.
Python Program
name = 'Oliver'
ch = name[4]
print(f'name[4] = {ch}')
Output
name[4] = e
2. Access character using negative index
In the following program, we take a string in name, and access the third character from the end of the string with index -3
.
Python Program
name = 'Oliver'
ch = name[-3]
print(f'name[-3] = {ch}')
Output
name[-3] = v
Summary
In this tutorial of Python Examples, we learned to how to access individual characters from a string using index, with examples.