我试图用python3格式化一组列。到目前为止我运气不太好。我设法把专栏打印出来,但我没办法把它们排成一行。我试图使每一列都是动态的,以便在需要打印不同的信息时能够进行调整。但是因为我试图在列格式中使用变量,所以我一直得到关键错误。你知道我怎么解决这个问题吗?在
Indicator :Min :Max
----------------------------------------------------------------------------
Traceback (most recent call last):
File "G:/test.py", line 154, in <module>
print('{heart:{heart_col_width}}:{motor:{motor_col_width}} {teen:{teen_col_width}{smoke: {smoke_col_width}}{obese:{obese_col_width}'.format(heart, motor, teen, smoke, obese ))
KeyError: 'heart'
这是我使用的代码。在
^{pr2}$
当你使用
format
函数不知道如何将"{whatever}"
中的任何与format(whatever)
中的whatever进行“匹配”或“连接”,对于解释器来说,它们之间没有任何关系。当.format
函数看到"{whatever}"
时,它将尝试在其调用中查找一个关键字参数whatever
,但没有。它只知道存在一个位置参数(这不是droid。。。呃。。。它正在寻找的论点)您可能想了解位置参数与关键字参数(checkthisSO thread)的区别,一般来说,您需要非常清楚地了解您所从事的任何Python开发的区别。在
知道了这一点,让我们回到
.format
方法:您需要显式地告诉
^{pr2}$.format
方法这两个whatever之间的联系:或许这样做会更清楚:
因此,在您的情况下,您可以:
由于使用了这些关键字参数,如果所有列的列宽都相同,则无需重新指定。您可以在字符串的不同部分重用它们:
检查这个string formatting tutorial(尤其是它的examples section)。它可能会给你一些另类的想法。在
相关问题 更多 >
编程相关推荐