簡體   English   中英

使用列表的所有元素格式化字符串

[英]Format string with all elements of a list

words = ['John', 'nice', 'skateboarding']
statement = "%s you are so %s at %s" % w for w in words

產生

File "<stdin>", line 1
statement = "%s you are so %s at %s" % w for w in words
                                           ^
SyntaxError: invalid syntax

我在這做錯了什么? 假設是:len(words)==語句中'%s'的數量

您還可以使用“splat”運算符使用新的.format樣式字符串格式:

>>> words = ['John', 'nice', 'skateboarding']
>>> statement = "{0} you are so {1} at {2}".format(*words)
>>> print (statement)
John you are so nice at skateboarding

即使您傳遞了一個生成器,這也有效:

>>> statement = "{0} you are so {1} at {2}".format(*(x for x in words))
>>> print (statement)
John you are so nice at skateboarding

雖然,在這種情況下,當您可以直接傳遞words時,不需要傳遞生成器。

我認為非常好的最后一種形式是:

>>> statement = "{0[0]} you are so {0[1]} at {0[2]}".format(words)
>>> print statement
John you are so nice at skateboarding
>>> statement = "%s you are so %s at %s" % tuple(words)
'John you are so nice at skateboarding'

有兩件事是錯的:

  • 您不能在沒有括號的情況下創建生成器表達式。 簡單地用w for w in words是python的無效語法。

  • %字符串格式化運算符需要元組,映射或單個值(不是元組或映射)作為輸入。 生成器不是元組,它將被視為單個值。 更糟糕的是,生成器表達式不會迭代:

     >>> '%s' % (w for w in words) '<generator object <genexpr> at 0x108a08730>' 

所以以下方法可行:

statement = "%s you are so %s at %s" % tuple(w for w in words)

請注意,您的生成器表達式實際上並不轉換單詞或從words列表中進行選擇,因此這里是多余的。 所以最簡單的方法是將列表轉換為tuple

statement = "%s you are so %s at %s" % tuple(words)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM