Python String Formatting: Padding Negative Numbers
Solution 1:
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(2if x>=0else3,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.
Solution 2:
According to here, you need a space before the type descriptor, so both
'% d'%(1)
and
'{: d}'.format(1)
result in (notice the space)
' 1'
aligning nicely with the result of the above called with -1:
'-1'
Solution 3:
The most concise, although maybe a bit unreadable, way that I can think of (at least in Python 3) would be a formatted string literal with nested curly braces, similar to the accepted answer. With this, the example from the accepted answer could be written as
l = [1, -1, 10, -10, 4]
new_l = [f"{x:0{2 + (x < 0)}d}" for x in l]
print(new_l)
with the same result:
['01', '-01', '10', '-10', '04']
Solution 4:
Use "{:03d}".format(n)
. The 0 means leading zeros, the 3 is the field width. May not be exactly what you want:
>>>for n in (-123,-12,-1,0,1,12,123, 1234):...print( '{:03d}'.format(n) )...
-123
-12
-01
000
001
012
123
1234
Solution 5:
zfill
actually pads with zeros at the left and considers negative numbers.
So n.zfill(3 if n < 0 else 2)
would do the trick.
Post a Comment for "Python String Formatting: Padding Negative Numbers"