0
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?

2 Answers2

3

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

ordem
  • 130
  • 2
  • 9
2

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'
jboockmann
  • 1,011
  • 2
  • 11
  • 27