Accessing Characters
Of course,
it is important to be able to access one or more characters read or stored by a
str variable,
and Python provides
an easy-to-use mechanism.
Look at the example below:
We consider a variable
s1 that holds the string "
caracter" (in Romanian).
The index of the first character is
0, and the last is
7, meaning
8-1, where
8 is the number of characters
contained by the object. By using a specific index and the operators "
[" and
"
]" together, we can access the characters:
EXAMPLE
Editor - lesson_8_strings.py
|
|
DETAILS
We cannot update a specific character value, as we will get an error from the interpreter:
However, we can update the entire value held by the variable
s1 through assignment, as we know.
Negative Index. Knowing the length of the string, we can access its characters from right to left using
negative indexes. Thus, the last character has the index
-1, the second to last,
-2, and so on.
Obviously, we get an error if we exceed the index; in this case,
-9 does not exist!
Run the program then proceed to the next page.