2013-01-17 76 views
2
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(字)==「%s」的的語句號

回答

5
>>> statement = "%s you are so %s at %s" % tuple(words) 
'John you are so nice at skateboarding' 
2

兩件事情是錯誤的:

  • 不能創建的周圍沒有括號發電機表達。簡單地把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) 
+1

'元組(W爲w的話)'是矯枉過正:)看到我的回答。 –

+0

@AlexeyKachayev:當然,但還有更多。我也許提交得太早了;現在更新。 –

6

你也可以使用新的.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 
相關問題