Access individual characters
We’ve already learned that strings are made of a contiguous set of characters. You can access individual characters in a string or obtain a range of characters in a string. Here is how it can be done:
>>> newString='Hello world!' >>> print (newString) H
In the example above we’ve created a string variable newString with the value of ‘Hello world!‘. We’ve then accessed the first character of the string using the square brackets. Since Python strings are zero-based (meaning that they start with 0), we got the letter H.
Here is another example. To obtain the letter w, we can use the following code:
>>> print (newString) w
To obtain a range of characters from a string, we need to provide the beginning and ending letter count in the square brackets. Here is an example:
>>> print (newString[0:3]) Hel
Notice how the character at the index 3 was not included in the output. The second number specifies the first character that you don’t want to include.
You can leave out the beginning or ending number in a range and get the reminder of the string:
>>> print (newString[:5]) Hello >>> print (newString[5:]) world!
If you want to start counting from the end of the string, you can use a negative index. The index of -1 includes the right-most character of the string:
>>> print (newString[-1]) !