6 Python f-strings tips and tricks f-строки в Python обеспечи | Python/ django
6 Python f-strings tips and tricks
f-строки в Python обеспечивают более читабельный, лаконичный и менее подверженный ошибкам способ форматирования строк, чем традиционное форматирование строк. Они обладают множеством полезных функций, которые обязательно пригодятся в повседневной работе.
1. String Interpolation
The most used f-string feature by far is string interpolation. All you need to do is wrap the value or variable in curly braces ({}) and you're good to go.
str_val = 'apples'
num_val = 42
print(f'{num_val} {str_val}') # 42 apples
2. Variable names
Apart from getting a variable's value, you can also get its name alongside the value.
str_val = 'apples'
num_val = 42
print(f'{str_val=}, {num_val = }') # str_val='apples', num_val = 42
3. Mathematical operations
Not syntactically unlike variable names, you can also perform mathematical operations in f-strings.
num_val = 42
print(f'{num_val % 2 = }') # num_val % 2 = 0
4. Printable representation
Apart from plain string interpolation, you might want to get the printable representation of a value.
str_val = 'apples'
print(f'{str_val!r}') # 'apples'
5. Number formatting
Numbers are a great candidate for this. If, for example, you want to trim a numeric value to two digits after the decimal, you can use the .2f format specifier.
price_val = 6.12658
print(f'{price_val:.2f}') # 6.13
6. Date formatting
Finally, dates can also be formatted the same way as numbers, using format specifiers. As usual, %Y denotes the full year, %m is the month and %d is the day of the month.
from datetime import datetime;
date_val = datetime.utcnow()
print(f'{date_val=:%Y-%m-%d}') # date_val=2021-07-09
String Formatting Best Practices
F-strings или как сделать код чуть более быстрым
@pythonl