python 3.4 string manipulation - truncating leading zeros

331 Views Asked by At

There are a number of existing posts on this topic, but I cannot get this simple piece of code to work correctly. I have tried many many times with no success...

per = 5


if per < 10 == True:
    ms = 'fwd_%sd' % str(per).zfill(2)
else:
    ms = 'fwd_%sd' % per

and

if per < 10 == True:
    a = format(per, 'fwd_02d')
else:
    a = 'fwd_%sd' % per

The result should be 'fwd_05d' but I can only get 'fwd_5d'.

Among others, I have seen:

Display number with leading zeros

Add leading zero python

Please help!

2

There are 2 best solutions below

5
On BEST ANSWER

You can use str.format, if you are actually doing nothing else but padding just use ms = 'fwd_{:02}d'.format(per) and forget the if/else, only numbers less than 10 will be padded with a 0. The 0 in {:02} is what to pad with and the 2 is the size to pad to.

ms = 'fwd_{:02}d'.format(per)

On another note if per < 10 == True: is the same as if per < 10:

0
On

You can just create a temp str variable, check if less than 10, and add a zero to the front if needed. Also, you shouldn't have an if statement and then check if it equals true. It is redundant and makes your code less readable.

per = 5

if per < 10:
    perStr = '0' + str(per)

print('fwd_' + perStr + 'd')