Search code examples
pythonnumber-formatting

Python string formatting: padding negative numbers


I would like to format my integers as strings so that, without the sign, they will be zero-padded to have at least two digits.

For example I want

1
-1
10
-10

to be

01
-01
10
-10

Specifically, I want different minimum string lengths for negative numbers (3) and non-negative numbers (2). Simple number padding as detailed here is insufficient. Is this possible?


Solution

  • you could use str.format, but adding 1 to the size to take the negative number into account here:

    l = [1,-1,10,-10,4]
    
    new_l = ["{1:0{0}d}".format(2 if x>=0 else 3,x) for x in l]
    
    print(new_l)
    

    result:

    ['01', '-01', '10', '-10', '04']
    

    it works because format accepts nested expressions: you can pass the size ({:02d} or {:03d}) as a format item too when saves the hassle of formatting the format string in a first pass.