Python F Strings Can Do More than You Thought
URL:
https://youtu.be/BxUxX1Ku1EQChannel/Host:
mCodingPublish Date:
2021.06.19Reviewed Date:
import.research.video.2021.11.18 (Private)
- 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