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.
The syntax to access a character from string x at index i is
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.
The following video tutorial from YouTube explains how to access characters in a string with nice visuals and explanation.
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.
name = 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.
name[-3] = v
In this tutorial of Python Examples, we learned to how to access individual characters from a string using index, with examples.