文字列への埋め込み

このページではPythonの文字列への変数埋め込みの方法について解説します。

文字列への変数埋め込み

Pythonで文字列に対して値を埋め込む方法はいくつかあるのですが、このページでは以下3つの方法について解説します。

  • f文字列
  • formatメソッド
  • printf 形式

f文字列

Python3.6以降、フォーマット済み文字列リテラルと呼ばれる記法が使用できます。f文字列と呼ばれることもあります。リテラルの先頭にfを記述し、埋め込みたい変数を中括弧でくくります。ただし、変数は予め定義する必要があります。

item = "apple"
text = f"There is an {item}."
print(text)  # There is an apple.

formatメソッド

文字列のformatメソッドを使用すると中括弧で置換フィールドを設定することができます。フィールドの設定方法は3つあり、中括弧単体、中括弧内に順序 or キーを指定する方法があります。

item1 = "apple"
item2 = "banana"

# 中括弧単体
text1 = "There are {} and {}."
print(text1.format(item1, item2))

# 順序指定
text2 = "There are {0} and {1}."
print(text2.format(item1, item2))

# キー指定
text3 = "There are {item1} and {item2}."
print(text3.format(**{"item1": item1, "item2": item2}))

# いずれも以下の通り出力される
# There are apple and banana.

printf形式

C言語のprintf形式と同様に%演算子に対しフォーマットすることができます。順番にタプルで指定する方法と、辞書でキーを指定する方法があります。ただし2021年現在、公式でも「よくある問題を引き起こす」といった記述があり、上で紹介した2つの方法と比較して廃れつつある印象があります。ただし、古いライブラリでは使用されているため知識として知っておくとコードを読み解く際に役に立つかと思います。

printf-style String Formatting
Note The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer formatted string literals, the str.format() interface, or template strings may help avoid these errors. Each of these alternatives provides their own trade-offs and benefits of simplicity, flexibility, and/or extensibility.

タプル

%sを列挙し、%演算子の後にタプルを指定します。

text = "There are %s, %s and %s."
f_text = text % ('apple', 'bananas', 'oranges',)
print(f_text) # There are apple, bananas and oranges.

辞書

%とsの間に丸括弧でキーを挟むと、辞書を指定することができます。以下のサンプルは、"first", "second", "third"がそれぞれキーになります。複雑なフォーマットを指定する場合はこちらを使用したほうがよいでしょう。

text = "There are %(first)s, %(second)s and %(third)s."

f_text = text % {'first': 'apple', 'second': 'bananas', 'third': 'oranges'}
print(f_text) # There are apple, bananas and oranges.