Python padding strings of different length

放肆的年华 提交于 2020-01-25 22:54:07

问题


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 of characters before a comma as in the list below.

 1148,
   39,
  365,
    6,
56524,

Cheers and thanks for your help :)


回答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))



回答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).




回答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))


来源:https://stackoverflow.com/questions/47803871/python-padding-strings-of-different-length

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!