Python String is an ordered sequence of unicode characters and stored as an array. In order to access characters in a String you need to specify string name followed by index in the square brackets. Since Python uses zero-based indexing, the first character of a string is at position 0, and for a string of length n, valid indices range from 0 to n-1.
In String in Python you can also use negative indexing which allows you to access characters starting from the end of the string. For example, -1 refers to the last character, -2 to the second last, and so on.
Here is an illustration of accessing characters in a Python string using both positive (left to right) and negative (right to left) indexing.
Getting characters from a string in Python example
s = "Hello World"
#first character
print(s[0])
#3rd character
print(s[2])
print('length of String', len(s))
#last character
print(s[len(s)-1])
Output
H l length of String 11 d
Getting characters using negative indexing
s = "Hello World"
# last character
print(s[-1])
print('length of String', len(s))
# first character by making the index negative
print(s[-(len(s))])
Output
d length of String 11 H
That's all for this topic Accessing Characters in Python String. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Python Tutorial Page
Related Topics
You may also like-
