python:f-strings

文書の過去の版を表示しています。


フォーマット済み文字列リテラル(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'
PS > python
Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> timeit.timeit("""name = "TomoYan";age = 99;
... '%s is %s.' % (name, age)""", number = 100000)
0.04157399999999711
>>> timeit.timeit("""name = "TomoYan";age = 99;
... '{} is {}.'.format(name, age)""", number = 100000)
0.05156640000001289
>>> timeit.timeit("""name = "TomoYan";age = 99;
... f'{name} is {age}.'""", number = 100000)
0.03830589999998324
>>>
  • python/f-strings.1585259525.txt.gz
  • 最終更新: 2020/03/27 06:52
  • by ともやん