This topic covers introduction of indexing in string.
Indexing in Strings
Index represent the position number of each character in a string
They are written in square braces []
Using index number in square braces, we refer to specific character in a string
Index number starts with zero 0
The first character of a string will have index number 0
str[0] refers to first character, str[1] refers to second character in a string and so on
Positive Index | 0 | 1 | 2 | 3 | 4 | 5 |
P | Y | T | H | O | N | |
Negative Index | -6 | -5 | -4 | -3 | -2 | -1 |
Above table represent positive and negative index number for string PYTHON.
When index is represented in a negative number, it represent character in a reverse order
Index number [-1] refers to last element or character in a string
Index number [-2] refers to second last character in a string
Code : Creating a string ‘PYTHON and displaying first and last character using index number
Assign a string ‘PYTHON’ to a variable
str = 'PYTHON'
Displaying first and last character of a string using index its position
str = 'PYTHON'
print('First Character:',str[0])
print('Last Character:',str[-1])
Output
First Character: P
Last Character: N