12. Formatting Strings - f-strings#
Appearing in Python3.6, f-strings are now the “recommended” approach to format strings. (Although, if you are using the gettext
module to create localized string for different countries, you’ll want to use the “new style” method from the previous section.
To create an f-string:
place the letter
f
orF
immediately before the start of a string literaluse variable names or expressions within curly braces to interpolate their values into the string.
f-strings use the same formatting language as the new-style formatting, just use a :
after the variable name or expression.
12.1. Formatting#
{:[fill][alignment][sign][minwidth][.][maxchars]type}
An initial colon (‘:’).
An optional fill character (default ‘ ‘) to pad the value string if it’s shorter than minwidth.
An optional alignment character:
‘<’ left (the default)
‘>’ right
‘^’ center
An optional sign for numbers. If
+
is specified, a plus symbol will be added to positive numbers. Negative numbers always have a minus sign.An optional minwidth.
An optional period (‘.’) to separate minwidth and maxchars if both are defined. If only one is defined, assumed to be maxchars
An optional maxchars. If this is the a float type, then this specifies the precision.
the type, which are the same as the old style
Type |
Description |
---|---|
s |
string |
d |
integer |
x |
hexadecimal integer |
o |
octal integer |
f |
float |
e |
float in exponential format |
g |
decimal or exponential float |
1year = 1838
2move_year = 1892
3school = "Duke University"
4city = "Trinity, North Carolina"
5print(f"In {year}, {school} was founded in {city}. {move_year-year} years later, {school} moved to Durham.")
In 1838, Duke University was founded in Trinity, North Carolina. 54 years later, Duke University moved to Durham.
As of Python 3.8, there’s also a useful shortcut to display variable names in the output. Just add =
after ther variable name or expression.
1year = 1838
2move_year = 1892
3school = "Duke University"
4city = "Trinity, North Carolina"
5print(f"In {year=}, {school=} was founded in {city}. {move_year-year=} years later, {school} moved to Durham.")
In year=1838, school='Duke University' was founded in Trinity, North Carolina. move_year-year=54 years later, Duke University moved to Durham.
1year = 1892
2print("123456789012345678901234567890")
3print(f"{year:+20d}")
4print(f"{year=:+20d}")
123456789012345678901234567890
+1892
year= +1892