====== フォーマット済み文字列リテラル (f-strings) ======
>>> str_val = 'abc'
>>> f'{str_val:>6}'
' abc'
>>> pi = 3.14159265358979
>>> f'pi: {pi:.2f}'
'pi: 3.14'
>>> f'pi: {pi:6.3f}'
'pi: 3.142'
>>> flt_val = 123456789.0123456
>>> f'float value: {flt_val:,.4f}'
'float value: 123,456,789.0123'
>>> flt_val = 1234.5678
>>> f'float value: {flt_val:>10,.2f}'
'float value: 1,234.57'
>>> f'float value: {flt_val:>14,.6f}'
'float value: 1,234.567800'
>>> 'int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}'.format(65536)
'int: 65536; hex: 0x10000; oct: 0o200000; bin: 0b10000000000000000'
>>> str = ' title '
>>> f'{str:->20}'
'------------- title '
>>> f'{str:-^20}'
'------ title -------'
>>> f'{str:-<20}'
' title -------------'
>>>
===== 書式編集のパフォーマンス比較 =====
$ python
Python 3.11.3 (main, Apr 5 2023, 00:00:00) [GCC 13.0.1 20230401 (Red Hat 13.0.1-0)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> timeit.timeit("""name = "TomoYan";age = 99;
... f'{name} is {age}.'""", number = 10000000)
2.247387803014135
>>> timeit.timeit("""name = "TomoYan";age = 99;
... '%s is %s.' % (name, age)""", number = 10000000)
2.269912829011446
>>> timeit.timeit("""name = "TomoYan";age = 99;
... '{} is {}.'.format(name, age)""", number = 10000000)
4.426570633018855
>>> timeit.timeit("""name = "TomoYan";age = 99;
... '{0} is {1}.'.format(name, age)""", number = 10000000)
5.005730772012612
>>> ^D
$ python
Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> timeit.timeit("""name = "TomoYan";age = 99;
... f'{name} is {age}.'""", number = 1000000)
0.2775605999999584
>>> timeit.timeit("""name = "TomoYan";age = 99;
... '%s is %s.' % (name, age)""", number = 1000000)
0.36503240000001824
>>> timeit.timeit("""name = "TomoYan";age = 99;
... '{} is {}.'.format(name, age)""", number = 1000000)
0.4583815999999956
>>> timeit.timeit("""name = "TomoYan";age = 99;
... '{0} is {1}.'.format(name, age)""", number = 1000000)
>>>
※**f-strings** の書式編集がもっとも高速である。\\
※次に、従来からの **%** 構文の書式編集、**{}** の置換フィールド、**{0}** の置換フィールド(インデックス番号)と続く。\\
===== 参考文献 =====
[[https://docs.python.org/ja/3/reference/lexical_analysis.html#formatted-string-literals|Pythonドキュメント 字句解析 - フォーマット済み文字列リテラル]]\\
[[https://qiita.com/QUANON/items/77ce3a9e7e33dbed489b|f-strings の使用例 - Qiita]]\\
[[https://qiita.com/tomotaka_ito/items/594ee1396cf982ba9887|Python文字列操作マスター - Qiita]]\\
[[https://realpython.com/python-f-strings/|Python 3's f-Strings: An Improved String Formatting Syntax (Guide) – Real Python]]\\
[[https://pyformat.info/|PyFormat: Using % and .format() for great good!]]\\