String alignment when printing in python

落花浮王杯 提交于 2021-01-28 15:28:45

问题


I want to output text like so:

Якета            : **************************** 1250.23 €
Обувки за футбол : ********************** 912.30 €
Екипи            : ************** 513.45 €
Топки            : ************ 502.52 €
T-SHIRTS         : ********* 420.19 €

How can I use placeholders to indent all colons to the length of the longest string - in this case Обувки за футбол?


回答1:


Probably, the most elegant way is to use the format method. It allows to easily define the space a string will use:

>>> name = 'Якета'
>>> asterisks = '****************************'
>>> price = 1250.23
>>> print '{0:17}: {1} {2} €'.format(name, asterisks, price)
Якета       : **************************** 1250.23 €

Should you need to programmatically define padding size (for instance, to dynamically accept larger strings instead of hard-coding its size), simply use ljust:

>>> name = 'Якета'
>>> asterisks = '****************************'
>>> price = 1250.23
>>> padding = 17
>>> print '{0}: {1} {2} €'.format(name.ljust(padding), asterisks, price)
Якета       : **************************** 1250.23 €

Considering the case when the maximum string size is unknown previously and the script must adapt to it, we only need to calculate the maximum string size and place it in padding:

>>> names = ['abc', 'defghijklm', 'op', 'q']
>>> asterisks = '****************************'
>>> price = 1250.23
>>> padding = max(map(len, strings))
>>> for name in names:
        print '{0}: {1} {2} €'.format(name.ljust(padding), asterisks, price)
abc       : **************************** 1250.23 €
defghijklm: **************************** 1250.23 €
op        : **************************** 1250.23 €
q         : **************************** 1250.23 €

This thread has a pretty similar issue.




回答2:


I would do something like this (somewhat "hackish"):

  • Get the longest string longest = len(longest_string). If you have your strings in a list then longest = len(max(mylist, key=len)).
  • Calculate for all strings spaces = longest - len(str).
  • Add spaces spaces to every end of string.


来源:https://stackoverflow.com/questions/35153862/string-alignment-when-printing-in-python

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