1

I'm without clues on how to do this in Python. The problem is the following: I have for example an orders numbers like:

1
2
...
234567

I need to extract only the 4 last digits of the order number and if the order number have less than 4 digits I will substitute with zeros.

The required output is like this:

0001
0002
...
4567

Any clues? I'm a bit lost with this one.

Best Regards,

André
  • 24,706
  • 43
  • 121
  • 178
  • The question is not an exact duplicate, as it looks for padding AND cutting to fix size – Don Mar 01 '13 at 22:53

2 Answers2

5

Try this:

>>> n = 234567
>>> ("%04d"%n)[-4:]
'4567'

Explanation (docs):

"%04d"%n --> get a string from the (d)ecimal n, putting leading 0s to reach 4 digits (if needed)

but this operation preserves all the digits:

>>> n = 7
>>> "%04d"%n
'0007'   
>>> n = 234567
>>> "%04d"%n
'234567'

So, if you want last 4 digits, just take the characters from position -4 (i.e. 4 chars from the right, see here when dealing with 'slice notation'):

>>> n = 234567
>>> ("%04d"%n)[-4:]
'4567'
Don
  • 16,928
  • 12
  • 63
  • 101
  • Great! It works. What does exactly the "%04d"?. Can you explain the magic? Thank you very much. – André Mar 01 '13 at 18:44
2

Something like the following:

>>> test = [1, 234567]
>>> for num in test:
        last4 = str(num)[-4:]
        print last4.zfill(4)

0001
4567
Jon Clements
  • 138,671
  • 33
  • 247
  • 280