Python F Strings Can Do More than You Thought



  • f strings that have a trailing = will print a statement like this:
x=7
print(f'{x=}')
# >>> x=7
print(f'{x =}')
# >>> x =7
print(f'{x = }')
# >>> x = 7
  • to print the repr of the value end the fstring with a !r:
x = "hello ✅"
print(f'{x!r}')
# >>> "hello ✅"
  • to print only ascii values end the fstring with a !a:
x = "hello ✅"
print(f'{x!a}')
# >>> "hello \u2705"
  • to print string values without quotes end the fstring with a !s:
x = "hello ✅"
print(f'{x!a}')
# >>> hello ✅

Formatting

  • format fstrings with a colon in the brace and the format on the right hand side

import datetime; print(f'{datetime.datetime.utcnow():%Y-%m-%d}')

Nested Formatting

num_value = 123.456
nested_format = ".2f"
print(f'{num_value:{nested_format}}')
# >>> 123.46

Backlinks