363

これは私のコードのほんの一部です:

print("Total score for %s is %s  ", name, score)

しかし、私はそれを印刷したい:

「(name) の合計スコアは (score) です」

ここnameで、 はリスト内の変数でありscore、整数です。それがまったく役立つ場合、これはPython 3.3です。

4

13 に答える 13

647

これを行うには多くの方法があります。-formattingを使用して現在のコードを修正する%には、タプルを渡す必要があります。

  1. タプルとして渡します。

    print("Total score for %s is %s" % (name, score))
    

要素が 1 つのタプルは のようになり('this',)ます。

これを行う他の一般的な方法を次に示します。

  1. 辞書として渡します。

    print("Total score for %(n)s is %(s)s" % {'n': name, 's': score})
    

新しいスタイルの文字列フォーマットもあり、少し読みやすいかもしれません:

  1. 新しいスタイルの文字列フォーマットを使用します:

    print("Total score for {} is {}".format(name, score))
    
  2. 数字で新しいスタイルの文字列フォーマットを使用します (同じものを複数回並べ替えたり印刷したりする場合に便利です):

    print("Total score for {0} is {1}".format(name, score))
    
  3. 明示的な名前で新しいスタイルの文字列フォーマットを使用します。

    print("Total score for {n} is {s}".format(n=name, s=score))
    
  4. 文字列を連結する:

    print("Total score for " + str(name) + " is " + str(score))
    

私の意見では、最も明確な2つは次のとおりです。

  1. 値をパラメーターとして渡すだけです。

    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
    
  2. Python 3.6 で新しいf-string フォーマットを使用します。

    print(f'Total score for {name} is {score}')
    
于 2013-03-08T03:52:57.977 に答える
63

それを印刷する方法はたくさんあります。

別の例で見てみましょう。

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}')
于 2016-08-11T13:07:38.753 に答える
15

簡単に言うと、私は個人的に文字列連結が好きです:

print("Total score for " + name + " is " + score)

Python 2.7 と 3.X の両方で動作します。

注: スコアがintの場合は、それをstrに変換する必要があります。

print("Total score for " + name + " is " + str(score))
于 2015-04-01T20:57:55.560 に答える
6
print("Total score for %s is %s  " % (name, score))

%s%dまたはで置き換えることができます%f

于 2016-03-03T16:51:36.773 に答える
5

scoreが数値の場合、

print("Total score for %s is %d" % (name, score))

スコアが文字列の場合、

print("Total score for %s is %s" % (name, score))

スコアが数値の場合は%d、文字列の%s場合は 、スコアが浮動小数点数の場合は%f

于 2016-07-11T19:53:48.190 に答える