Because it made me think a little.
This is a well-introduced method and I think it's a basic grammar.
'{0:05d}'.format(12) #=> '00012'
It has nothing to do with zero filling, but it looks like the following to fill with spaces.
'{0:5d}'.format(12) #=> ' 12'
In Python, you can't use variables in fields like {0: 05d}
, so you can't "dynamically specify the number of digits to get a string" in this notation.
Therefore, it can be realized by the following method.
python
# -*- coding: utf-8 -*-
max = 10000 #<=Assuming this will be dynamic
#Get the maximum digit
max_len = len(str(max))
#Target numerical value (appropriate this time)
test = 123
###Zero padding with maximum digits for the target number###
# `zfill`When using
output = str(test).zfill(max_len)
print(output) #=> '00123'
#When using rjust
output = str(test).rjust(max_len,'0')
print(output) #=> '00123'
By using zfill
, variables can be used for the number of digits specified by the argument.
Also, if you use rjust
, you can fill it with non-zero characters by specifying a character other than 0
as the second argument.
(@Matobaa san taught me how to use rjust
. Thankx @matobaa san!)
Recommended Posts