-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
  • 7,271
  • 11
  • 40
  • 76

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
  • 50,140
  • 28
  • 121
  • 140
3

You can use str.ljust:

>>> lst = [477 , 4770, 47711,]
>>> [str(x).ljust(5) for x in lst]
['477  ', '4770 ', '47711']
tobias_k
  • 81,265
  • 12
  • 120
  • 179
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
  • 229
  • 4
  • 15
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
  • 4,056
  • 4
  • 21
  • 36
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