-3

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"]
user3675188
  • 6,563
  • 9
  • 29
  • 66

5 Answers5

3

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']
Bhargav Rao
  • 41,091
  • 27
  • 112
  • 129
3

You can use str.ljust:

>>> lst = [477 , 4770, 47711,]
>>> [str(x).ljust(5) for x in lst]
['477  ', '4770 ', '47711']
tobias_k
  • 74,298
  • 11
  • 102
  • 155
1

You can use this solution.

input = [477 , 4770, 47711,]
[str(i).ljust(5) for i in input]

results in...

['477  ', '4770 ', '47711']
Tristan Maxson
  • 365
  • 1
  • 13
1

Alternately to .format you can use ljust

example:

>>> x = 'padme'
>>> x = x.ljust(10, ' ')
>>> x
'padme     '

There also exists rjust to add leading characters.

NDevox
  • 3,751
  • 4
  • 18
  • 32
0

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.

BehoyH
  • 1