Slice a Python string by index
What is string slice and how to use string slicing
Slicing means accessing a range of characters in a string. We can do slicing by providing two indices separated by a colon.
The first value is the start index and the second value is the to index. The start index is inclusive and to index is exclusive.
pystr = 'Python from java2s.com'
iscool = 'is cool!'
print pystr[0]# www . j a v a2 s.c o m
print pystr[2:5]
print iscool[:2]
print iscool[3:]
print iscool[-1]
aString = 'abcd'
final_index = -len(aString)
print aString[-3:-1]
print aString[-4]
print aString[2:]
print aString[1:]
print aString[:-1]
print aString[:]
The code above generates the following result.
tag = '<a href="http://www.java2s.com">Web site</a>'
print tag[9:30]
print tag[32:-4]
The code above generates the following result.
Just as indexing we can do slicing from the right of a list.
To slice from the end of a list we can omit the second index and use negative value for the first index.