f'{hoge}'はフォーマット文字列リテラル(f-strings)[Python]
Kaggleを眺めていると見慣れない記法を発見。
x = str(x)for punct in puncts:x = x.replace(punct, f' {punct} ')return xん? f’ {punct} ’ ってなんぞ?
調べてみるとこれはf-strings(フォーマット文字列リテラル)でPython 3.6で追加された新機能だということが分かった。
f-stringsを使うと
>>> name = 'Fred'>>> age = 42>>> f'He said his name is {name} and he is {age} years old.'He said his name is Fred and he is 42 years old.のように変数名を文字列に埋めることができる。
参考にしたサイト
The new f-strings in Python 3.6 | Seasoned & Agile
PyFormat: Using % and .format() for great good!
Python 3.6の新機能f-strings(フォーマット文字列リテラル)について - Read -> Blog
f-stringsに限らず文字列まわりはバージョンで書き方が増えているので、独習Pythonで現行の書き方をまとめて確認しておくと無駄がない。
※本記事にはアフィリエイト広告を含みます。