Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

python - String formatting: Columns in line

I am trying to format the string so everything lines up between the two.

APPLES                           $.99                           214                       
kiwi                             $1.09                           755 

I am trying this by doing:

fmt = ('{0:30}{1:30}{2:30}'.format(Fruit,price,qty))

How would I get a column to line up? I read the docs but I am confused. I was thinking that the {1:30} would make it 30 spaces, then it would print the next item, but it appears that it is 30 spaces from where the previous item ended.

Thanks

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

str.format() is making your fields left aligned within the available space. Use alignment specifiers to change the alignment:

'<' Forces the field to be left-aligned within the available space (this is the default for most objects).

'>' Forces the field to be right-aligned within the available space (this is the default for numbers).

'=' Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form ‘+000000120’. This alignment option is only valid for numeric types.

'^' Forces the field to be centered within the available space.

Here's an example (with both left and right alignments):

>>> for args in (('apple', '$1.09', '80'), ('truffle', '$58.01', '2')):
...     print '{0:<10} {1:>8} {2:>8}'.format(*args)
...
apple         $1.09       80
truffle      $58.01        2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...