I want to padding spaces of each input item if it is less than 5 characters,
Then padding each to 5 characters long.
How to do it with Python
input = [477 , 4770, 47711]
output = ["477 ", "4770 ", "47711"]
I want to padding spaces of each input item if it is less than 5 characters,
Then padding each to 5 characters long.
How to do it with Python
input = [477 , 4770, 47711]
output = ["477 ", "4770 ", "47711"]
Use format
>>> input = [477 , 4770, 47711,]
>>> ["{:<5}".format(i) for i in input]
['477 ', '4770 ', '47711']
>>> list(map("{:<5}".format , input)) # Just Another Way using map
['477 ', '4770 ', '47711']
You can use str.ljust
:
>>> lst = [477 , 4770, 47711,]
>>> [str(x).ljust(5) for x in lst]
['477 ', '4770 ', '47711']
You can use this solution.
input = [477 , 4770, 47711,]
[str(i).ljust(5) for i in input]
results in...
['477 ', '4770 ', '47711']
Alternately to .format
you can use ljust
example:
>>> x = 'padme'
>>> x = x.ljust(10, ' ')
>>> x
'padme '
There also exists rjust
to add leading characters.
You'll have to iterate over the entire string to count the digits. But in this case I think you could get away with a count() (which yes, is still technically in iteration) and then have if statements that will append the appropriate number of spaces to the string.