-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,871
  • 10
  • 33
  • 72

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
  • 45,811
  • 27
  • 120
  • 136
3

You can use str.ljust:

>>> lst = [477 , 4770, 47711,]
>>> [str(x).ljust(5) for x in lst]
['477  ', '4770 ', '47711']
tobias_k
  • 78,071
  • 11
  • 109
  • 168
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
  • 197
  • 2
  • 14
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,916
  • 4
  • 20
  • 33
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