LoginSignup
8
8

More than 1 year has passed since last update.

【Python】f文字列

Last updated at Posted at 2021-06-13

はじめに

Pythonで文字列の中に変数を組み込む場合、Python3.6でf文字列が導入されるまでは、次のようにformatメソッドを使うのが一般的でした。

sample1.py
fruits = ['apple', 'orange', 'grape']

for i, fruit in enumerate(fruits):
    print('{}: {}'.format(i, fruit))
$ python sample1.py
0: apple
1: orange
2: grape

ただ、formatメソッドは上記の例を見て分かるように少し冗長な書き方になります。さらに、文字列の中に組み込む変数が増えた場合、括弧と変数の対応関係が直感的に分かりづらくなる欠点があります。

f文字列

そこで登場したのがf文字列です。先の例は次のように書き換えることができます。

sample2.py
fruits = ['apple', 'orange', 'grape']

for i, fruit in enumerate(fruits):
    print(f'{i}: {fruit}')
$ python sample2.py
0: apple
1: orange
2: grape

出力結果は全く同じですが、書き方がシンプルになったと思います。文字列の中に組み込む変数が増えた場合でも、どの括弧にどの変数が埋め込まれるのかというのが直感的に分かります。

f文字列と配列

f文字列に組み込む変数として配列を指定すると、次のように配列としてそのまま展開されます。

sample3.py
fruits = ['apple', 'orange', 'grape']

print(f'fruits: {fruits}')
$ python sample3.py
fruits: ['apple', 'orange', 'grape']

f文字列と改行&エスケープ

f文字列の中で改行したい場合、次のように改行文字(\n)を入れるだけです。

sample4.py
fruits = ['apple', 'orange', 'grape']

print(f'{fruits[0]}\n{fruits[1]}\n{fruits[2]}')
$ python sample4.py
apple
orange
grape

改行文字を単なる文字列として扱いたい場合、次のようにバックスラッシュでエスケープするか、もしくはfの前(後ろでもOK)にrを追加するとできます。後述しますが、rはr文字列(raw文字列)のrとなります。

sample5.py
fruits = ['apple', 'orange', 'grape']

print(f'{fruits[0]}\\n{fruits[1]}\\n{fruits[2]}')
print(rf'{fruits[0]}\n{fruits[1]}\n{fruits[2]}')
$ python sample5.py
apple\norange\ngrape
apple\norange\ngrape

f文字列とr文字列

先に述べたr文字列(raw文字列)ですが、これは読んで字のごとく括弧の中の変数を展開せずにそのままの文字列として扱います。

sample6.py
fruits = ['apple', 'orange', 'grape']

for i, fruit in enumerate(fruits):
    print(r'{i}: {fruit}')
$ python sample6.py
{i}: {fruit}
{i}: {fruit}
{i}: {fruit}

さいごに

f文字列をPythonのデフォルトの文字列にしようという動きもあるので、f文字列を知っておいて損はないと思います。他の言語でもf文字列と同様の機能があり使われることも多いので、個人的にはデフォルトになってもいいのではと思います。

8
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
8