0

So I know that I can use either the "%" or ".format" syntax to format string, particularly to trim the end of string to a set number of characters:

>>> print("%s" % "12345678990")    
12345678990
>>> print("%.5s" % "12345678990")
12345

Is there any way to trim the beginning of the string using string formatting (not slicing, etc)? The desired output would be:

>>> print("%<lst3>" % "12345678990")    
990

I have tried the following, to no avail:

"%.-3s"

"%.=3s"

"%.:3s"

"%.:-3s"

And so on.

I have seen nothing in the docs about this, but would be happy to be proven wrong! Any help is appreciated.

NWaters
  • 1,163
  • 1
  • 15
  • 27

3 Answers3

0

well for this problem you have to use slicing.

print ("12345678990"[8:])
#or
print ("12345678990"[-3:])

Understanding Python's slice notation will be useful to you.

sam-pyt
  • 1,027
  • 15
  • 26
0

For strings, taking a slice is more Pythonic:

>>> "12345678990"[-3:]
'990'

Bear in mind the "wrap-around" behavior of negative numbers in slicing and indexing.

Daniel Pryden
  • 59,486
  • 16
  • 97
  • 135
0

You can do like this :

 print("%s" % "12345678990"[-3:])
Akash KC
  • 16,057
  • 6
  • 39
  • 59