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,

1
  • The question is not an exact duplicate, as it looks for padding AND cutting to fix size Commented Mar 1, 2013 at 22:53

2 Answers 2

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'
Sign up to request clarification or add additional context in comments.

1 Comment

Great! It works. What does exactly the "%04d"?. Can you explain the magic? Thank you very much.
2

Something like the following:

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

0001
4567

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.