
String Indexing in Python
In this lesson of the Nigiara Python course, I will explain how string indexing works.
What is indexing? In Python, strings (text) are a sequence of characters. For example, a word or phrase can be seen as a combination of individual characters placed one after the other. Each character within a string has an index, which is a numeric position within the string itself.
The first character of a string has an index of 0, the second character has an index of 1, and so on. String indexing is the process of accessing a specific character within a string using its index.
In Python, string indexing works similarly to accessing elements of a list.
Strings in Python are iterable objects. Therefore, you can read each character within a string using its numeric index.
To access a specific character within a string, you need to indicate the index of the character in square brackets.
string[index]
Here's a practical example.
Assign a string to the variable "text".
>>> text = "Python is a programming language"
To read the first character of the string, type text[0]
>>> text[0]
In this case, the command returns the letter "P", because it is the first letter of the string "Python is a programming language".
P
Remember that indexing always starts at 0, not 1. So the first character of a string always has index 0.
Now type text[1] to read the second character of the string.
>>> text[1]
The output result is the character "y".
y
In Python, string indexing can also be a negative number.
In this case, the index starts from the last character of the string, where -1 corresponds to the last character, -2 to the second-to-last, and so on.
For example, type text[-1]
>>> text[-1]
Python accesses the last character of the string and returns the character "e".
Now type the command text[-2]
>>> text[-2]
The result is the second-to-last character of the string, which is "g".
In short, string indexing in Python allows you to access individual characters within a string through their index number, which can be both positive and negative. With a positive index, you access characters from the first to the last, from left to right, while with a negative index, you access characters from the last to the first, from right to left.