为什么python字符串格式需要一个元组?为什么列表不起作用?

时间:2019-06-24 00:56:22

标签: python

我很惊讶python的百分比样式格式将不接受列表,而似乎仅接受元组。这里的元组有什么特别之处?为什么列表会引发错误?

In [1]: '%s %s' % ('hello', 'kilojoules')                                                     
Out[1]: 'hello kilojoules'

In [2]: '%s %s' % ['hello', 'kilojoules']                                                     
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-764f27542c69> in <module>
----> 1 '%s %s' % ['hello', 'kilojoules']

TypeError: not enough arguments for format string

3 个答案:

答案 0 :(得分:3)

用于格式化字符串的方式是一种特殊的语法。在显示的列表示例中,它将非元组(列表)转换为字符串,然后尝试将其用于格式化。

您可以使用format方法来完成您想做的事情。

In [1]: "{} {}".format(*['hello', 'kilojoules'])

无论如何,建议使用这种方式as it is preferred

答案 1 :(得分:2)

此外,借助python3.6中的最新更新,您可以使用如下所示的f-String:

> great = "hello"
> name = "kilojoules"

> f"{great} {name}"
'hello kilojoules'

website很好地总结了执行此操作的不同方法。

答案 2 :(得分:1)

文档(https://python-reference.readthedocs.io/en/latest/docs/str/formatting.html)直接回答您的问题:“如果格式说明符需要单个参数,则值可能是单个非元组对象。否则,值必须是具有指定项目数的元组格式字符串或单个映射对象(例如字典)。”列表都不是,所以不会。

就像其他人指出的那样,您可以只使用.format获得更现代的方法,甚至使用更现代的f字符串,就像您的原始示例一样简洁:

one_way = '{} {}'.format(*['hello', 'kilojoules'])
lst = ['hello', 'kilojoules']
another_way = f'{lst[0]} {lst[1]}'