'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 1:[1]
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 2:[2]
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 3:[3]
Use zfill:
inp_list = [1,-1,10,-10,4]
out_list = [str(n).zfill(3 if n<0 else 2) for n in inp_list]
print(out_list)
result:
['01', '-01', '10', '-10', '04']
Solution 4:[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:[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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alex Thomas |
| Solution 2 | simon |
| Solution 3 | Jatin Verma |
| Solution 4 | nigel222 |
| Solution 5 | Newage99 |
