Compared with traditional string formatting ,Python Of f-strings Provides a more readable 、 More concise and error free string formatting . They contain many useful functions , These functions will certainly come in handy in daily use . Let's take a look at some of them .
up to now , Most commonly used f The string function is string interpolation . All you need to do is enclose values or variables in curly braces ( {}
) in , Then you can start .
str_val = 'apples'
num_val = 42
print(f'{num_val} {str_val}') # 42 apples
In addition to getting the value of the variable , You can also get its name next to the value . This is particularly useful when debugging , And through =
Add an equal sign after the variable name in curly braces ( ) Easy to finish .
please remember , Spaces in braces have been taken into account , Therefore, adding spaces around the equal sign can make the results more readable .
str_val = 'apples'
num_val = 42
print(f'{str_val=}, {num_val = }') # str_val='apples', num_val = 42
Syntactically different from variable names , You can also f Perform mathematical operations in a string . You can put mathematical expressions in curly braces , If you add an equal sign , You will get the expression and its result .
num_val = 42
print(f'{num_val % 2 = }') # num_val % 2 = 0
In addition to pure string interpolation , You may also want to get a printable representation of the value . Use this repr()
The function is already easy to complete .!r
f-strings By appending a To provide shorter Syntax .
str_val = 'apples'
print(f'{str_val!r}') # 'apples'
Besides ,f-strings It can also be used to format - So... In the name f. To add formatting to a value , You can add colons ( :
), Followed by the format specifier . If you also want to print the name of the variable , This can also be combined with the previous equal sign .
Numbers are a good candidate . for example , If you want to trim the value to two decimal places , You can use .2f
Format specifier .
price_val = 6.12658
print(f'{price_val:.2f}') # 6.13
Last , Dates can also be formatted like numbers , Use format specifiers . As usual ,%Y
Indicates the whole year ,%m
It's the month , It's the month %d
One of these days .
from datetime import datetime;
date_val = datetime.utcnow()
print(f'{date_val=:%Y-%m-%d}') # date_val=2021-07-09