Python String is an ordered sequence of 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. Note that index is 0 based and valid range for string of length n is 0..(n-1).
In String in Python you can also use negative indexing. When negative number is used as index String is accessed backward so -1 refers to the last character, -2 second last and so on.
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-