Skip to content Skip to sidebar Skip to footer

Python Padding Strings Of Different Length

So I have a problem I know can be solved with string formatting but I really don't know where to start. What I want to do is create a list that is padded so that there is n number

Solution 1:

The most straight-forward way is to use the str.rjust() function. For example:

your_list = [1148, 39, 365, 6, 56524]

for element in your_list:
    print(str(element).rjust(5))

And you get:

 1148
   39
  365
    6
56524

There are also str.center() and str.ljust() for string justification in other directions.

But you can also do it via formatting:

your_list = [1148, 39, 365, 6, 56524]

for element in your_list:
    print("{:>5}".format(element))

Solution 2:

See Format Specification Mini-Language.

You are looking for something like "{:5d},".format(i) where i is the integer to be printed with a width of 5.

For a variable width: "{:{}d},".format(i, width).

Solution 3:

Assuming you know what n is you can do: '{:>n}'.format(number)

So if you have a list of integers and wanted to format it as above you could do:

numbers = [1148, 39, 365, 6, 56524]
result = '\n'.join(('{:>5},'.format(x) for x in numbers))

Post a Comment for "Python Padding Strings Of Different Length"