サンプル集  >  Python  >  f文字列
f文字列
2023/07/17

f文字列の利用例です。

◆環境
OS Windows 10 Home 22H2 64bit OS x64 プロセッサ
Python 3.9.6
VS Code 1.80.0

formatとf文字列の使用例です。Pythonのバージョンにより利用できる機能が増えているようです。

3.5以前 format
3.6以降 f文字列
3.8以降 =で変数名を合わせて表示

testfstring.py
 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
val = 123
print( "val={0} by format".format( val ) )
print( "val={val} by format".format( val=val ) )

print( f"val={val} by f-strint" )

# 書式指定
print( f"val={val:05} by f and 05" )

# =を付けると変数名も合わせて表示される
print( f"{val=} by f and =" )

実行してみます。

PS C:\pywork> py .\testfstring.py
val=123 by format
val=123 by format
val=123 by f-strint
val=00123 by f and 05
val=123 by f and =

期待通りに表示されました。

▲ PageTop  ■ Home


Copyright (C) 2023 ymlib.com