2016-05-16 10 views
2

これは最も簡単な質問です。しかし、次のようにタプルの個々の値を出力しようとしました。フォーマットされたタプル値の出力

mytuple=('new','lets python','python 2.7') 

>>> print "%{0} experience, %{1} with %{2} " %mytuple 
Traceback (most recent call last): 
    File "<pyshell#25>", line 1, in <module> 
    print "%{0} experience, %{1} with %{2} " %mytuple 
ValueError: unsupported format character '{' (0x7b) at index 1 

次のように出力したいと思います。

"new experience, lets python with python 2.7" 

私はそれがどこで行われたのか覚えていません。これは、フォーマットされたタプルを出力して、タプルの値をアンパックすることです。

+0

あなたは '%'メソッドと'{}' .format'メソッドを選択して、それに固執します。 –

+0

よろしく!ありがとう@ TadhgMcDonald-Jensen、それは完全に正常に動作します。私は不必要な括弧を追加していました。それは間違っていました。 –

答えて

5

代わりのprintfスタイルの整形とstr.formatを混合、いずれかを選択します。

printf-style formatting

>>> mytuple = ('new','lets python','python 2.7') 
>>> print "%s experience, %s with %s" % mytuple 
new experience, lets python with python 2.7 

str.format

>>> print "{0} experience, {1} with {2}".format(*mytuple) 
new experience, lets python with python 2.7 
1

あなたが問題を解決するためのフォーマット方法とアスタリスクを使用することができます。

あなたは方法のいずれかをすることができます詳細はthis link

>>mytuple=('new','lets python','python 2.7') 
>>print "{0} experience, {1} with {2} ".format(*mytuple) 
new experience, lets python with python 2.7 
1

を参照してください。しかし、フォーマットは簡単で、より簡単に管理できます。あなただけprintfstr.formatを混ぜ

>>> a = '{0} HI {1}, Wassup {2}' 
>>> a.format('a', 'b', 'c') 
'a HI b, Wassup c' 
>>> b = ('a' , 'f', 'g') 
>>> a.format(*b) 
'a HI f, Wassup g' 
1

、あなたがそれらのいずれかを選択します。必要があります。

>>> tuple1 = ("hello", "world", "helloworld") 
>>> print("%s, %s, %s" % tuple1) 

か:

>>> tuple1 = ("hello", "world", "helloworld") 
>>> print("{}, {}, {}".format(*tuple1)) 
0

少しだけ変更する必要があります

>>> mytuple=('new','lets python','python 2.7') 
>>> print "%s experience, %s with %s " %mytuple 
new experience, lets python with python 2.7 
>>> 
関連する問題