Printing with fixed field widths

时间:2015-12-07 12:59:24

标签: python python-3.x format

This is my code so far. It does what I want it just doesn't have a fixed widths when printing the string.

def PrintTuple(tuple) :
    formatted = '{}, {:<15} {:<5} {:<5} {:<5} £{:<5}'.format(tuple[4], '', tuple[3], tuple[0], tuple[2], tuple[1])
    print(formatted)

For example it will print :

Potter,                 Harry Potter 12349 Wizard £30000

Capaldi,                 Peter Capaldi 13128 Timelord £50 

I want it to print so that they have fixed widths of :

15, 15, 5, 15, 7

2 个答案:

答案 0 :(得分:0)

您的格式说明符中有一个迷路{},而您的字段宽度并不像您所说的那样。尝试:

def PrintTuple(tup) :
    formatted = u'{:<15} {:<15} {:<5} {:<15} £{:<7}'.format(tup[4], tup[3], tup[0], tup[2], tup[1])
    print(formatted)

给出:

PrintTuple((12349, 30000, 'Wizard', 'Harry Potter', 'Potter'))
PrintTuple((13128, 50, 'Timelord', 'Peter Capaldi', 'Capaldi'))

Potter          Harry Potter    12349 Wizard          £30000  
Capaldi         Peter Capaldi   13128 Timelord        £50

答案 1 :(得分:0)

使用此字符串:

'{}, {:<15} {:<5} {:<5} {:<5} £{:<5}'

您正在打印6个值,但仅为其中五个提供固定宽度,而第一个打印的数据具有任何宽度,因此也会打破剩余值的格式。您需要为第一个值提供宽度才能工作:

'{:<15}, {:<15} {:<5} {:<5} {:<5} £{:<5}'

另外,如果你的字符串比宽度限定符长,那么字符串不会被str.format()方法截断,这是你必须自己做的事情。如果你没有,那么长于分配宽度的字段也会破坏格式。看看这两个&#34;向导&#34;和&#34;时间领主&#34;都比你为它们分配的{:<5}宽度长。