Python: f-string(f 文字列)と「:」の便利な使い方

TwitterFacebookHatena
  • 公開:2021-12-7
  • 更新:2023-10-26
  • 文章量:2962
  • Python

TL;DR

f-string は式を埋め込める文字リテラルである。先頭に f を付け、f{式}と書く。{} の中に、全ての Python 式を書くことができる。

セパレーター

:, とすると、カンマのセパレーターを入れる。

a = 10000000000
print(f'{a:,}')
# 10,000,000,000

print(f'{a:_}')
# 10_000_000_000

文字の位置を指定する

: の後ろに整数をつけると、フィールドの最小の文字幅を指定できる。揃えたいときに便利。 : の後ろにキャレット、小なり、大なり を置くと文字方向を指定できる。

  • :^ は、文字を中寄せ
  • :< は、文字を左寄せ
  • :> は、文字を右寄せ

そして、数値分の残りを指定の文字で繰り返して埋める。

passwd = 'password'

print(f'{passwd:*^20}')
# ******password******

print(f'{passwd:*<20}')
# password************

print(f'{passwd:ば>20}')
# ばばばばばばばばばばばばpassword

:<10 だと、空白 10 個分が埋められる。

key = 'hello'
value = 1.234

f = f'{key} = {value}'
print(f)
# hello = 1.234

f = f'{key:<10} = {value:.4f}'
# :<10     最小フィールド幅
# :.4f     有効桁数(4桁)
print(f)
# 'hello'    = 1.2340

改行

冗長なコードは改行して表示することができる。

n = [
    ('a', 1),
    ('b', 2),
    ('c', 3),
]
for i, (item, count) in enumerate(n):
    print(f'{i}: '
          f'{item:<10} = '
          f'{count}')

# 0: a          = 1
# 1: b          = 2
# 2: c          = 3

フォーマット指定

フォーマットを指定する。

fl = 1111
print(f'値は{fl:.3f}である!')
# 値は1111.000である!

入れ

子 入れ子 {{}} でフォーマットを指定する。

point = 3
fv = 222.1111999

print(f'{fv:.{point}f}')
# 222.111

バイナリデータ変換

バイナリデータに変換する。

fl = 45
print(f'bit は {fl:b}')
# bit は 101101

print(f'hex は {fl:x}')
# hex は 2d

print(f'int は {fl:d}')
# int は 45

日付の整形

日付を整形する。

import datetime
d = datetime.datetime(2022, 1, 4, 3, 15, 59)
print(f'{d:%Y-%m-%d %H:%M:%S}')
# 2022-01-04 03:15:59

置換 (conversion)

値に対して str() を呼ぶ !s 、 repr() を呼ぶ !r 、 ascii() を呼ぶ !a がサポートされている。

name = '12345'
print(f'hello {name!r}')
# hello '12345'

print(f'hello {name}')
# hello 12345

置換 (conversion) フィールドにより書式変換前に型の強制変換が実施されます。通常、値の書式変換は __format__() によって実施されます。しかしながら、場合によっては、文字列として変換することを強制したり、書式指定の定義をオーバーライドしたくなることもあります。 __format__() の呼び出し前に値を文字列に変換すると、通常の書式変換の処理は飛ばされます。現在 3 つの変換フラグがサポートされています: 値に対して str() を呼ぶ !s 、 repr() を呼ぶ !r 、 ascii() を呼ぶ !astring --- 一般的な文字列操作 — Python 3.10.0b2 ドキュメント

計算

計算を行う。

s = 10
print(f'{s + 1}')
# 11

w = 'world '
f'hello {w * 3}'
# 'hello world world world'

import math
print(f'{math.pi:.2f}')
# 3.14

テキスト

テキストを代入する。

w = 'world'
f'hello {w}'
# 'hello world'

file_name = 'flower.jpg'
alt_name = '花の写真です'
f'<img src="{file_name}" alt="{alt_name}">'
# <img src="flower.jpg" alt="花の写真です">
``

`

#### 式をそのまま表示する
`=` は名前を表示する。`=`` の直後に `:` を入れると、配置や幅を指定できる。
```python
a = 'apple'
b = 'banana'

print(f'{a}, {b}')
# apple, banana

# = を付ける
print(f'{a=}, {b=}')
# a ='apple', b ='banana'

# 配置.幅
print(f'{a=:10.2}, {b=:.3}')
# a = ap        , b =ban

関数

関数の結果を返す。

def func():
    return 'hoge'

print(f'{func()}')
# hoge

リスト

リストの要素を返すこともできる。

img = ['flower.jpg', '花の写真です']
f'<img src="{img[0]}" alt="{img[1]}">'
# <img src="flower.jpg" alt="花の写真です">

w = ['apple', 'banana', 'cherry']
f'{w[1].title()}'
# 'Banana'

式を複数入れられる。

w = ['apple', 'banana', 'cherry']
f'{w[0].capitalize()} is not the same as...{w[1].rjust(20)}.'
# 'Apple is not the same as...              banana.'

Python: f-string(f 文字列)と「:」の便利な使い方