Enclosed {} in Python format strings
Mar. 13th, 2025 10:53 amSeems apparent, but only after occasionally found this.
And even:
But this way isnʼt allowed:
but we can override it with a trick:
Not an often case but still useful.
>>> "{}".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.
no subject
Date: 2025-03-13 09:53 am (UTC)Dreamwidth and GitHub use different flavors of Markdown.
no subject
Date: 2025-03-13 12:33 pm (UTC)Чем хорош маркдаун, так это обилием стандартов. Выбирай, не хочу.