Pythonで複数の引数を印刷する

これは私のコードのほんの一例です。

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

しかし、私はこれをプリントアウトしたいのです。

"名前の合計スコアは(スコア)&quotです。

ここで、nameはリスト内の変数、scoreは整数です。これはPython 3.3ですが、少しでも参考になれば幸いです。

これにはいろいろな方法があります。現在のコードを % 形式で修正するには、タプルを渡す必要があります。

1.タプルとして渡す。

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

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

その他の一般的な方法を紹介します。

2.辞書として渡す。

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

また、新しいスタイルの文字列のフォーマットもあり、少し読みやすくなっているかもしれません。

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

    print("Total Score for {} is {}".format(name, score))

4.数字で新スタイルの文字列フォーマットを使用する(順序を変えたり、同じものを何度も印刷するのに便利)。

    print("{0}の総得点は{1}".format(name, score))

5.明示的な名前で新スタイルの文字列フォーマットを使用する。

    print("Total Score for {n} is {s}".format(n=name, s=score))

6.文字列を連結する。

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

私の意見では、この2つが一番わかりやすいです。

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

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

上の例でprint`によって自動的にスペースを挿入されたくない場合は、`sep`パラメータを変更してください。

    print("Total score for ", name, " is ", score, sep='')

Python 2を使用している場合、最後の2つは使用できません。しかし、この動作を `__future__` からインポートすることができます。

    from __future__ import print_function

8.Python 3.6 の新しい f-文字列フォーマットを使用してください。

    print(f'{name}のトータルスコアは{score}')
解説 (4)

シンプルに考えれば、個人的には文字列の連結が好きです。

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

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

注意:もし score が int であれば、 str に変換する必要があります。

print("Total score for " + name + " is " + str(score))
解説 (0)

やってみてください。

print("Total score for", name, "is", score)
解説 (0)