繁体   English   中英

使用变量格式在python中格式化字符串

[英]Format string in python with variable formatting

如何使用变量来格式化我的变量?

cart = {"pinapple": 1, "towel": 4, "lube": 1}
column_width = max(len(item) for item in items)
for item, qty in cart.items():
    print "{:column_width}: {}".format(item, qty)

> ValueError: Invalid conversion specification

要么

(...):
    print "{:"+str(column_width)+"}: {}".format(item, qty)

> ValueError: Single '}' encountered in format string

不过,我能做的是首先构造格式化字符串,然后对其进行格式化:

(...):
    formatter = "{:"+str(column_width)+"}: {}"
    print formatter.format(item, qty)

> lube    : 1
> towel   : 4
> pinapple: 1

不过看起来很笨拙。 没有更好的方法来处理这种情况吗?

好的,问题已经解决了,这里是未来参考的答案:变量可以嵌套,所以这很好用:

for item, qty in cart.items():
    print "{0:{1}} - {2}".format(item, column_width, qty)

python 3.6 开始,你可以使用f-strings 来实现更简洁的实现:

>>> things = {"car": 4, "airplane": 1, "house": 2}
>>> width = max(len(thing) for thing in things)
>>> for thing, quantity in things.items():
...     print(f"{thing:{width}} : {quantity}")
... 
car      : 4
airplane : 1
house    : 2
>>> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM