*Memo:
- My post explains f-strings.
- My post explains Format Specification with f-strings (1).
- My post explains Format Specification with f-strings (2).
- My post explains Format Specification with f-strings (3).
- My post explains Format Specification with f-strings (5).
- My post explains format().
- My post explains format_map().
- My post explains a string.
:[f][a][s][z][#][0][w][g][.p][t]
can format a string with f-strings as shown below:
<Format a string with Decimal() by 'f' or 'F'>:
from decimal import Decimal v = Decimal(value='1234.5555555555') # | 10 | print(v) # 1234.5555555555 # | 10 | print(f'"{v:.20f}"') print(f'"{v:.20F}"') # "1234.55555555550000000000" # | 20 | print(f'"{v:.15f}"') print(f'"{v:.15F}"') # "1234.555555555500000" # | 15 | print(f'"{v:.10f}"') print(f'"{v:.10F}"') print(f'"{v:f}"') print(f'"{v:F}"') # "1234.5555555555" # | 10 | print(f'"{v:.6f}"') print(f'"{v:.6F}"') # "1234.555556" # | 6 | print(f'"{v:.2f}"') print(f'"{v:.2F}"') # "1234.56" print(f'"{v:.1f}"') print(f'"{v:.1F}"') # "1234.6" print(f'"{v:.0f}"') print(f'"{v:.0F}"') # "1235" print(f'"{v:#.0f}"') print(f'"{v:#.0F}"') # "1235." print(f'"{v:,.20f}"') print(f'"{v:,.20F}"') # "1,234.55555555550000000000" # | 20 | print(f'"{v:,f}"') print(f'"{v:,F}"') # "1,234.5555555555" # | 10 | print(f'"{v:_.20f}"') print(f'"{v:_.20F}"') print(f'"{v:_f}"') print(f'"{v:_F}"') # ValueError: invalid format string
from decimal import Decimal v1 = Decimal(value='nan') v2 = Decimal(value='inf') print(f'"{v1:f} {v2:f}"') print(f'"{v1:F} {v2:F}"') # "NaN Infinity"
*Decimal()
without str
gets an improper value.
from decimal import Decimal v = Decimal(value=1234.5555555555) # | 10 | print(v) # 1234.555555555499950060038827359676361083984375 # | 42 | print(f'"{v:.20f}"') print(f'"{v:.20F}"') # "1234.55555555549995006004" # | 20 | print(f'"{v:.15f}"') print(f'"{v:.15F}"') # "1234.555555555499950" # | 15 | print(f'"{v:.10f}"') print(f'"{v:.10F}"') # "1234.5555555555" # | 10 | print(f'"{v:.6f}"') print(f'"{v:.6F}"') # "1234.555556" # | 6 | print(f'"{v:.2f}"') print(f'"{v:.2F}"') # "1234.56" print(f'"{v:.1f}"') print(f'"{v:.1F}"') # "1234.6" print(f'"{v:.0f}"') print(f'"{v:.0F}"') # "1235" print(f'"{v:#.0f}"') print(f'"{v:#.0F}"') # "1235." print(f'"{v:f}"') print(f'"{v:F}"') # "1234.555555555499950060038827359676361083984375" # | 42 | print(f'"{v:,.20f}"') print(f'"{v:,.20F}"') # "1,234.55555555549995006004" # | 20 | print(f'"{v:,f}"') print(f'"{v:,F}"') # "1,234.555555555499950060038827359676361083984375" # | 42 | print(f'"{v:_.20f}"') print(f'"{v:_.20F}"') print(f'"{v:_f}"') print(f'"{v:_F}"') # ValueError: invalid format string
from decimal import Decimal v1 = Decimal(value=float('nan')) v2 = Decimal(value=float('inf')) print(f'"{v1:f} {v2:f}"') print(f'"{v1:F} {v2:F}"') # "NaN Infinity"
Top comments (0)