Skip to content Skip to sidebar Skip to footer

Python - How To Add Zeros To And Integer/string?

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

Solution 1:

Try this:

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

Explanation (docs):

"%04d"%n --> get a stringfrom the (d)ecimal n, putting leading 0sto 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'

Solution 2:

Something like the following:

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

0001
4567

Post a Comment for "Python - How To Add Zeros To And Integer/string?"