logo

Pythonで文字列を補間する方法 📂プログラミング

Pythonで文字列を補間する方法

f-string

f-stringは、Python 3.6から使用可能で、文字列補間の中で最も簡単で便利な方法だ。文字列の前にfをつけ、文字列の中で変数を{変数}のように使えばいい。

>>> name = 'An, Yujin'
>>> birthday = '2003'
>>>
>>> print(f'The leader of IVE is {name}, and she was born in {birthday}.')
The leader of IVE is An, Yujin, and she was born in 2003.

str.format()

文字列に.format()メソッドを使用して補間できる。f-stringの方法に比べて可読性が著しく劣る。変数の位置を空の中括弧{}で空けておき、メソッドに順番通りに引数を入れればいい。

>>> name = 'An, Yujin'
>>> birthday = '2003'
>>>
>>> print('The leader of IVE is {}, and she was born in {}.'.format(name, birthday))
The leader of IVE is An, Yujin, and she was born in 2003.
>>>
>>> print('The leader of IVE is {name}, and she was born in {birthday}.'.format(name='An, Yujin', birthday='2003'))
The leader of IVE is An, Yujin, and she was born in 2003.

Cスタイル補間法

%を使用して次のように補間することができる。

>>> print('The leader of IVE is %s, and she was born in %d.' % ('An, Yujin', 2003))
The leader of IVE is An, Yujin, and she was born in 2003.

Template

stringモジュールのTemplateクラスを活用して補間することができる。

>>> from string import Template
>>>
>>> template = Template("The leader of IVE is $name, and she was born in $birthday.")
>>> str = template.substitute(name='An, Yujin', birthday=2003)
>>> print(str)
The leader of IVE is An, Yujin, and she was born in 2003.

環境

  • OS: Windows11
  • Version: Python 3.11.5