f文字列(f-string)の使い方【Python】

f文字列の記事のアイキャッチPython

f文字列の使い方

f文字列を使えば文字列に変数を埋め込むことが出来ます。

基本的な使い方は以下のように文字列の前にfをつけ、 { } で変数を囲むだけです。
すると変数が展開されます。

lang = 'python'
print(f'lang is {lang}')
# lang is python

もちろん複数使うことも可能です。

name = 'John'
age = 30
print(f'My name is {name} . im {age} years old.')
# My name is John . im 30 years old.

当たり前ですが、{ }内で演算や関数も使えます。

print(f'{3 + 7}')
# 10
print(f'{max(2, 5)}')
# 5

エスケープシーケンス

文字列に付き物なのがエスケープシーケンスです。
f文字列でもエスケープシーケンスは使えます。

むしろ使えないと困りますね😅

name = 'John'
age = 30
print(f'My name is {name} .\nim {age} years old.')
# My name is John .
# im 30 years old.

エスケープシーケンスをエスケープシーケンスとして扱わないようにするraw文字列(rの接頭辞)があるのですが、これもf文字列と併用することが出来ます。

接頭辞の順番はどっちでも良いみたい。frでもrfでもOK

print(r'hello \n hello')
# hello \n hello

greeting = 'こんにちは'
print(f'hello \n hello {greeting}')
# hello 
#  hello こんにちは

print(fr'hello \n hello {greeting}')
# hello \n hello こんにちは

print(rf'hello \n hello {greeting}')
# hello \n hello こんにちは

f文字列内で { , } を使う

{ }で変数を埋め込むことはOKだと思いますが、文字列内で{ , }を普通に使いたければどうするのでしょうか?

気にせずに使うとエラーになってしまいます。

print(f'this is curly braces { ')
# SyntaxError: f-string: expecting '}'
print(f'this is curly braces }{')
# SyntaxError: f-string: single '}' is not allowed

結論としては
{{{
}}}
で使うことができるのです。

print(f'this is curly braces {{ ')
# this is curly braces { 
print(f'this is curly braces }}{{')
# this is curly braces }{

他の埋め込み方法

pythonで変数を文字列に埋め込む方法はいくつかある。

その一つとしてf文字列があるが、他にも以下のようなformat()%演算子 を使う方法もある。

'My name is {} . im {} years old.'.format('John', 30)
# My name is John . im 30 years old.

'My name is %s . im %d years old.' % ('John', 30)
# My name is John . im 30 years old.

むしろこれらの方法の方がf文字列よりも良く見ると思う。
f文字列がpythonのバージョン3.6から導入されたからあんまり普及してないのかな?

参考

2. 字句解析 — Python 3.8.17 ドキュメント

コメント