I Cannot Seem To Find The Correct Formatting Spec For Preceding Zeroes In Python
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 p
Solution 1:
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'
Solution 2:
Use zfill
:
john = 2
johnmod = str(john).zfill(4)
print(johnmod) # Prints: 0002
Solution 3:
You were nearly there:
johnmod = format(john, "04d")
Solution 4:
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.
Post a Comment for "I Cannot Seem To Find The Correct Formatting Spec For Preceding Zeroes In Python"