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(words) == ステートメント内の '%s' の数

4

3 に答える 3

6

.format「splat」演算子を使用して、新しいスタイルの文字列フォーマットを使用することもできます。

>>> 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
于 2013-01-17T14:06:48.787 に答える
5
>>> statement = "%s you are so %s at %s" % tuple(words)
'John you are so nice at skateboarding'
于 2013-01-17T13:48:19.467 に答える
2

次の 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代わりにリストを a にキャストすることです。

statement = "%s you are so %s at %s" % tuple(words)
于 2013-01-17T13:51:51.883 に答える