Python で%記号を出力する
このチュートリアルでは、Python の print() 関数を使用して%記号を出力するメソッドを紹介します。
Python で%記号を表示する
通常、次のコードスニペットに示すように、Python の print() 関数を使用してコンソールに%記号を書き込むための特別なトリックは必要ありません。
print("This is the % sign")
出力:
This is the % sign
Python の print() 関数を使用して、コンソールに%記号を出力しました。この問題は、同じ print() 関数で%s プレースホルダーと別の%記号を使用して文字列を書き込むときに発生します。次のコードはエラーなしで実行されます。
text = "some text"
print("this is %s" % text)
出力:
this is some text
ただし、上記の 2つのコードを組み合わせようとすると、次の結果のコードスニペットでエラーが発生します。
text = "some text"
print("this is a % sign with %s" % text)
エラー:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-6006ad4bf52e> in <module>()
1 text = "some text"
----> 2 print("this is a % sign with %s"%text)
TypeError: not enough arguments for format string
このエラーは、%記号の書き込みにエスケープ文字を使用していないためにスローされます。
Python で%記号をエスケープ文字で出力
この場合、エスケープ文字も\文字ではなく%文字になります。次のコードスニペットは、%記号を別の%エスケープ文字でエスケープする方法を示しています。
text = "some text"
print("this is a %% sign with %s" % text)
出力:
this is a % sign with some text
上記のコードでは、%記号と文字列変数の両方を print() 関数と%エスケープ文字で出力しました。
Python で str.format() 関数を使用して%記号を出力する
文字列フォーマットを使用して、単一の print() 関数内に文字列変数を含む%記号を出力することもできます。str.format() 関数はこの目的に使用できます。str は、文字列変数の代わりに {} を使用した出力を含む文字列であり、format() 関数には、出力するすべての文字列変数が含まれます。次のコードスニペットは、Python で文字列形式で%記号を出力する方法を示しています。
text = "some text"
print("this is a % sign with {0}".format(text))
出力:
this is a % sign with some text
上記のコードでは、str.format() 関数を使用して、Python の単一の print() 関数内に文字列変数を含む%記号を記述しました。
以前の方法は廃止され、まもなく廃止されるため、この方法が推奨されます。
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn