Reputation: 189
When adding decimal places, it's as simple as
john = 2
johnmod = format(john, '.2f')
print(johnmod)
and I get 2.00 back, as expected. But, what's the format spec for adding preceding zeros? I would like for the output to be 0002, and the only spec I've found with Google for that is using %04d, which did not work. If it matters, I am running Python 3.3 on windows.
Upvotes: 3
Views: 557
Reputation: 394825
Several Pythonic ways to do this,:
First using the string formatting minilanguage, using your attempted method, first zero means the fill, the 4 means to which width:
>>> format(2, "04")
'0002'
Also, the format minilanguage:
>>> '{0:04}'.format(2)
'0002'
the specification comes after the :
, and the 0
means fill with zeros and the 4
means a width of four.
New in Python 3.6 are formatted string literals:
>>> two = 2
>>> f'{two:04}'
'0002'
Finally, the str.zfill
method is custom made for this:
>>> str(2).zfill(4)
'0002'
Upvotes: 6
Reputation: 308111
format(john, '05.2f')
You can add the leading 0
to a floating point f
format as well, but you must add the trailing digits (2) and the decimal point to the total.
Upvotes: 1
Reputation: 16240
Use zfill
:
john = 2
johnmod = str(john).zfill(4)
print(johnmod) # Prints: 0002
Upvotes: 2