Sometimes, you need to get a single character from a string. For example, if the website knows the user's first name and surname, and at some point, you need to output it as A. Ivanov. The computer will need to take the first character from the name to do it. Python has a suitable operation, which we'll look at today.
Extract element by indexes
Suppose you want to display only the first letter of the name Alexander. It looks like this:
first_name = 'Alexander'
print(first_name[0]) # => A
The operation with square brackets with a digit extracts an element by its index — the character's position inside the string. Indexes start with 0 in almost all programming languages. Therefore, to get the first character, you need to specify the index 0
. The last element index is equal to the string length minus one. Accessing an index outside the string will cause an error:
# The string length is 9, so the last index is 8
first_name = 'Alexander'
print(first_name[8]) # => r
print(first_name[9])
IndexError: string index out of range
To better consolidate your new knowledge, look at the code below and think about what it produces:
magic = '\nyou'
print(magic[1]) # => ?
There are, of course, non-standard situations. For example, you may need to output an element from the end, and it's from an expression with many characters. In this case, you can use a negative index and make your life much easier.
Negative indices
You're allowed to use negative indices. In this case, we access characters starting from the end of the string. -1
is the index of the last character, -2
is the penultimate, and so on. Unlike direct indexing, the countdown goes from -1
:
first_name = 'Alexander'
print(first_name[-1]) # => r
You can use variables as well as numbers as an index. Look at the example below. Here we have an index inside the square brackets. It's not a number but a variable. This code will cause the same result and output A:
first_name = 'Alexander'
index = 0
print(first_name[index]) # => A
If you only want to get a few characters from an expression, you don't need to write many lines of code or extract the element using an index. You can also use a negative index to make it easier to output characters from the end of an expression.