[英]why does python string formatting need a tuple? Why doesn't a list work?
我很驚訝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
格式化字符串的方式是一種特殊的語法。 在顯示的列表示例中,它將非元組(列表)轉換為字符串,然后嘗試將其用於格式化目的。
您可以使用format
方法來完成您想做的事情。
In [1]: "{} {}".format(*['hello', 'kilojoules'])
無論如何,建議這樣做, 因為它是首選 。
另外,借助python3.6中的最新更新,您可以使用如下所示的f-String:
> great = "hello"
> name = "kilojoules"
> f"{great} {name}"
'hello kilojoules'
該網站很好地總結了不同的方法。
該文檔( 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]}'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.