Knowledge Base
Authentication is disabled (development mode).

python f-strings examples

Edit

example examples f-string f-strings format py python string

f = 1.23
print(f"{f}") # 1.23
print(f"{f:e}") # 1.230000e+00
print(f"{f:f}") # 1.230000
print(f"{f:.2f}") # 1.23
print(f"{f:g}") # 1.23

u = 0x400
print(f"{u}") # 1024
print(f"{u:x}") # 400
print(f"{u:#x}") # 0x400
print(f"{u:#06x}") # 0x0400
print(f"0x{u:08x}") # 0x00000400

i = 16
print(f"{i:+}") # +16
print(f"{f:+.6f}") # +1.230000
i = -16
print(f"{i:+}") # -16

s="Hmm..."
print(f"->{s:<8}<-") # ->Hmm...  <-
print(f"->{s:>8}<-") # ->  Hmm...<-
print(f"->{s:^16}<-")# ->     Hmm...     <-

value = 1
print(f"{0 if value < 2 else value}") # 0
value = 2
print(f"{0 if value < 2 else value}") # 2

obj = type('', (object,), { "foo": "bar" })()
print(f"{obj.foo}") # bar