stringname[Start: End: Step]
G | I | R | I | S | H |
0 | 1 | 2 | 3 | 4 | 5 |
-6 | -5 | -4 | -3 | -2 | -1 |
Strings can be indexed, with the first character having index 0
>>> mystr = "GIRISH"
>>> mystr
'GIRISH'
>>> mystr[0] # character in position 0
'G'
>>> mystr[1] # character in position 1
'I'
>>> mystr[5] # character in position 5
'H'
>>> mystr[6] # Out of range Index will throw IndexError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
Negative Indexing start from -1
>>> mystr[-1] # last character
'H'
>>> mystr[-6] # first character of the given string (refer above for negative indexing)
'G'
>>> mystr[-7] # Out of range Index will throw IndexError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
Indexing is used to obtain individual characters, slicing allows you to obtain substring. Start is always included, and the end always excluded. s[:i] + s[i:]
is always equal to s, where s is a string.
>>> mystr[0:2] # characters from position 0 (included) to 2 (excluded)
'GI'
>>> mystr[2:5] # characters from position 2 (included) to 5 (excluded)
'RIS'
Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.
>>> mystr[:2] # character from the beginning to position 2 (excluded)
'GI'
>>> mystr[4:] # characters from position 4 (included) to the end
'SH'
>>> mystr[-2:] # characters from the second-last (included) to the end
'SH'
>>> mystr[:-2] # going up to but not including the last 2 chars.
'GIRI'
>>> mystr[1:44] # out of range slice indexes are automatically handled
'IRISH'
>>> mystr[44:]
''
>>> mystr[::2] # step value is 2
'GRS'
>>> mystr[::-2]
'HII'
>>> mystr[:]
'GIRISH'
>>> mystr[::-1] # String Reverse
'HSIRIG'
References
- https://docs.python.org/3/tutorial/introduction.html
Learn more about Python features in our upcoming blog articles.
Happy Learning!