Python: Integers formatting


#1

Hi,

I am having trouble trying to format a simple list of integers: The aim is to format integers so when I print them I get double digits. So basically -1 shoud become -01, 0 becomes 00, 1 becomes 01 etc. I have manage to make it work for positive numbers but all the negative values don’t seem to change. I’m not looking for a work around, I would like to know the correct python expression if there is any.

Any ideas?
@Helvetosaur, @djordje, @AndersDeleuran

levels = range(-3,21)

for level in levels:
    print(level,'LVL {:02d}'.format(level))

"""
Output:
(-3, 'LVL -3') --> needs to be + (-3, 'LVL -03')
(-2, 'LVL -2') --> needs to be + (-3, 'LVL -02')
(-1, 'LVL -1')  --> needs to be + (-3, 'LVL -01')
(0, 'LVL 00')
(1, 'LVL 01')
(2, 'LVL 02')
(3, 'LVL 03')
"""

-Miguel


(Willem Derks) #2

Hi Miguel,

This seems to work:


def LeadingZerosTest():
    
    levels = range(-3,21)
    
    for level in levels:
        print  (level , 'LVL '+leading_zero_integer(level))
    
    
    
def leading_zero_integer(integer):
    
    if integer < 0:
    # expect an extra character
        return '{:03d}'.format(integer)
    
    else:
        return '{:02d}'.format(integer)

result:

(-3, 'LVL -03')
(-2, 'LVL -02')
(-1, 'LVL -01')
(0, 'LVL 00')
(1, 'LVL 01')
(2, 'LVL 02')
(3, 'LVL 03')
...

#3

Hi Willem,

I’m guessing python is counting the “-” minus sign.

Thanks again,

-Miguel


(Willem Derks) #4

Actually this was just a trial and error for me…no clue if it is pythonesque.


#5

I’m guessing python is measuring the len() of the string created, hence the extra character needed.


#6

This gives what you’re looking for. The space in the format string (’% 03d’) will print a space for positive values and a ‘-’ for negative ones.

levels = range(-3,21)
for level in levels:
    print( level, 'LVL % 03d'%level)