netch80: (Default)
netch80 ([personal profile] netch80) wrote2025-03-13 10:53 am

Enclosed {} in Python format strings

Seems apparent, but only after occasionally found this.


>>> "{}".format(math.pi)
'3.141592653589793'
>>> "{:{}}".format(math.pi, 'f')
'3.141593'
>>> "{:{}}".format(math.pi, '.14f')
'3.14159265358979'

>>> f"{math.pi}"
'3.141592653589793'
>>> pr=10
>>> f"{math.pi:.{pr}e}"
'3.1415926536e+00'


And even:


>>> "{:{}}".format(math.pi, '.16e')
'3.1415926535897931e+00'
>>> f"{math.pi:{'.12e'}}"
'3.141592653590e+00'


But this way isnʼt allowed:


>>> f"{math.pi:{\".12e\"}}"
  File "", line 1
    f"{math.pi:{\".12e\"}}"
                           ^
SyntaxError: f-string expression part cannot include a backslash


but we can override it with a trick:


>>> f"{math.pi:{'.12e'}}"
'3.141592653590e+00'
>>> f"""{math.pi:{".12e"}}"""
'3.141592653590e+00'


Not an often case but still useful.
gegmopo4: (Default)

[personal profile] gegmopo4 2025-03-13 09:45 am (UTC)(link)

\".12e\" is not valid Python syntax. But ".12e" is, and in Python 3.12 you can use the same inner and outer quotes: ```

f"{math.pi:{".12e"}}" '3.141592653590e+00' You can also use a backslash in nested expressions in f-string (this was the main motivation of implementing a new parser for f-strings): f"{"\n".join("abc")}" 'a\nb\nc' ```

gegmopo4: (Default)

[personal profile] gegmopo4 2025-03-13 09:53 am (UTC)(link)

Dreamwidth and GitHub use different flavors of Markdown.

vitus_wagner: My photo 2005 (Default)

[personal profile] vitus_wagner 2025-03-13 12:33 pm (UTC)(link)

Чем хорош маркдаун, так это обилием стандартов. Выбирай, не хочу.