简体   繁体   English

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

[英]Format string in python with variable formatting

How can I use variables to format my variables?如何使用变量来格式化我的变量?

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

or要么

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

> ValueError: Single '}' encountered in format string

What I can do, though, is first construct the formatting string and then format it:不过,我能做的是首先构造格式化字符串,然后对其进行格式化:

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

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

Looks clumsy, however.不过看起来很笨拙。 Isn't there a better way to handle this kind of situation?没有更好的方法来处理这种情况吗?

Okay, problem solved already, here's the answer for future reference: variables can be nested, so this works perfectly fine:好的,问题已经解决了,这里是未来参考的答案:变量可以嵌套,所以这很好用:

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

Since python 3.6 you can use f-strings resulting in more terse implementation: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