在python中打印时的字符串对齐 [英] String alignment when printing in python

查看:97
本文介绍了在python中打印时的字符串对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这样输出文本:

Якета            : **************************** 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 Обувки за футбол?

推荐答案

可能,最优雅的方法是使用 format 方法.它允许轻松定义字符串将使用的空间:

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 €

是否需要以编程方式定义填充大小(例如,动态接受较大的字符串而不是对其大小进行硬编码),只需使用 just :

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 €

考虑到最大字符串大小以前未知并且脚本必须适应的情况,我们只需要计算最大字符串大小并将其放在 padding 中:

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.

这篇关于在python中打印时的字符串对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆