python字符串格式化列中的行 [英] python string formatting Columns in line

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

问题描述

我正在尝试格式化字符串,以便在两者之间排列所有内容.

苹果 $.99 214猕猴桃 1.09 755 美元

我正在尝试这样做:

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

如何让一列对齐?我阅读了文档,但我很困惑.我在想 {1:30} 会使它成为 30 个空格,然后它会打印下一个项目,但它似乎与前一个项目结束的地方相距 30 个空格.

谢谢

解决方案

str.format() 使您的字段在可用空间内左对齐.使用对齐说明符来改变对齐方式:

<块引用>

'<' 强制字段在可用空间内左对齐(这是大多数对象的默认设置).

'>' 强制字段在可用空间(这是数字的默认值).

'=' 强制将填充放在在数字之前签名(如果有).这用于打印字段格式为+000000120".此对齐选项仅适用于数字类型.

'^' 强制字段在可用空间.

这是一个例子(左右对齐):

<预><代码>>>>对于 (('apple', '$1.09', '80'), ('truffle', '$58.01', '2')) 中的参数:...打印'{0:<10} {1:>8} {2:>8}'.format(*args)...苹果 1.09 美元 80松露 $58.01 2

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

解决方案

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

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

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