mytxt = "12345678"
print(mytxt)
temptxt = mytxt[::-1]
print(temptxt)
temptxt = temptxt[0:3]
print(temptxt)
mytxt = temptxt[::-1]
print(mytxt)
I want to get the last 3 characters from the string, how to make this code shorter?
mytxt = "12345678"
print(mytxt)
temptxt = mytxt[::-1]
print(temptxt)
temptxt = temptxt[0:3]
print(temptxt)
mytxt = temptxt[::-1]
print(mytxt)
I want to get the last 3 characters from the string, how to make this code shorter?
The string in mytxt has the following index in each character
-----------------------------------------
mytxt = 1 2 3 4 5 6 7 8
-----------------------------------------
index(positive) = 0 1 2 3 4 5 6 7
index(negative) = -8 -7 -6 -5 -4 -3 -2 -1
The negative index allows us to access the n-last character in the string
And by utilizing the slice function whose syntax goes like
[start:end:increment]
so
print(mytxt[-3::])
Leaving the initial and increment blank means we're using the default value,
which are 0 for the initial and 1 for increment, or better still, just omit the second colon
print(mytxt[-3:])
The comprehensive summary of slice function can be found here
As pointed out by @hiro-protagonist you can use Python's slice notation to retrieve the last three characters of a string as follows:
mytxt = "12345678"
print(mytxt[-3:]) # yields '678'