これは私のコードのほんの一部です:
print("Total score for %s is %s ", name, score)
しかし、私はそれを印刷したい:
「(name) の合計スコアは (score) です」
ここname
で、 はリスト内の変数でありscore
、整数です。それがまったく役立つ場合、これはPython 3.3です。
これは私のコードのほんの一部です:
print("Total score for %s is %s ", name, score)
しかし、私はそれを印刷したい:
「(name) の合計スコアは (score) です」
ここname
で、 はリスト内の変数でありscore
、整数です。それがまったく役立つ場合、これはPython 3.3です。
これを行うには多くの方法があります。-formattingを使用して現在のコードを修正する%
には、タプルを渡す必要があります。
タプルとして渡します。
print("Total score for %s is %s" % (name, score))
要素が 1 つのタプルは のようになり('this',)
ます。
これを行う他の一般的な方法を次に示します。
辞書として渡します。
print("Total score for %(n)s is %(s)s" % {'n': name, 's': score})
新しいスタイルの文字列フォーマットもあり、少し読みやすいかもしれません:
新しいスタイルの文字列フォーマットを使用します:
print("Total score for {} is {}".format(name, score))
数字で新しいスタイルの文字列フォーマットを使用します (同じものを複数回並べ替えたり印刷したりする場合に便利です):
print("Total score for {0} is {1}".format(name, score))
明示的な名前で新しいスタイルの文字列フォーマットを使用します。
print("Total score for {n} is {s}".format(n=name, s=score))
文字列を連結する:
print("Total score for " + str(name) + " is " + str(score))
私の意見では、最も明確な2つは次のとおりです。
値をパラメーターとして渡すだけです。
print("Total score for", name, "is", score)
上記の例でスペースが自動的に挿入されないようにするには、パラメーターを次print
のように変更します。sep
print("Total score for ", name, " is ", score, sep='')
Python 2 を使用している場合、 は Python 2 の関数ではないため、最後の 2 つを使用できませんprint
。ただし、この動作は からインポートできます__future__
。
from __future__ import print_function
Python 3.6 で新しいf
-string フォーマットを使用します。
print(f'Total score for {name} is {score}')
それを印刷する方法はたくさんあります。
別の例で見てみましょう。
a = 10
b = 20
c = a + b
#Normal string concatenation
print("sum of", a , "and" , b , "is" , c)
#convert variable into str
print("sum of " + str(a) + " and " + str(b) + " is " + str(c))
# if you want to print in tuple way
print("Sum of %s and %s is %s: " %(a,b,c))
#New style string formatting
print("sum of {} and {} is {}".format(a,b,c))
#in case you want to use repr()
print("sum of " + repr(a) + " and " + repr(b) + " is " + repr(c))
EDIT :
#New f-string formatting from Python 3.6:
print(f'Sum of {a} and {b} is {c}')
簡単に言うと、私は個人的に文字列連結が好きです:
print("Total score for " + name + " is " + score)
Python 2.7 と 3.X の両方で動作します。
注: スコアがintの場合は、それをstrに変換する必要があります。
print("Total score for " + name + " is " + str(score))
print("Total score for %s is %s " % (name, score))
%s
%d
またはで置き換えることができます%f
score
が数値の場合、
print("Total score for %s is %d" % (name, score))
スコアが文字列の場合、
print("Total score for %s is %s" % (name, score))
スコアが数値の場合は%d
、文字列の%s
場合は 、スコアが浮動小数点数の場合は%f