Home  >  Article  >  Backend Development  >  Python F-Strings are more powerful than you think

Python F-Strings are more powerful than you think

WBOY
WBOYforward
2023-04-17 09:01:021280browse

Python F-Strings are more powerful than you think

Format string literals – also known as f strings – have been around since Python 3.6, so we all know what they are and how Use them. However, you may not be aware of some of the more practical and convenient features of f-strings. So let this article take you through some of the features of f-strings, and hopefully you will use these great f-strings features in your daily coding.

Date and time formatting

It’s very common to apply number formatting using f-strings, but did you know you can also format date and timestamp strings? ?

import datetime
today = datetime.datetime.today()
print(f"{today:%Y-%m-%d}")
# 2023-02-03
print(f"{today:%Y}")
# 2023

f-strings Date and time can be formatted just like using the datetime.strftime method. It's great when you realize that there are many more formats than the few mentioned in the documentation. Python strftime also supports all formats supported by the underlying C implementation, which may vary from platform to platform, which is why it is not mentioned in the documentation. Having said that, you can still take advantage of these formats and use for example %F which is equivalent to %Y-%m-%d or %T which is equivalent to %H:%M:%S, it’s also worth mentioning that %x and %X are the locale’s preferred date and time formats respectively. The use of these formats is obviously not limited to f-strings. For a complete list of time formats see:
https://manpages.debian.org/bullseye/manpages-dev/strftime.3.en.html

Variable Names and Debugging

One of the recent additions to the f-string feature (as of Python 3.8) is the ability to print variable names and values:

x = 10
y = 25
print(f"x = {x}, y = {y}")
# x = 10, y = 25
print(f"{x = }, {y = }")# Better! (3.8+)
# x = 10, y = 25

print(f"{x = :.3f}")
# x = 10.000

This feature is called "Debug" , can be used in combination with other modifiers . It also preserves spaces, so f"{x = }" and f"{x=}" will produce different strings.

String representation

When printing a class instance, __str__default uses the class method to represent a string. However, if we want to force the use of __repr__, we can use the !r conversion flag:

class User:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name

def __str__(self):
return f"{self.first_name} {self.last_name}"

def __repr__(self):
return f"User's name is: {self.first_name} {self.last_name}"

user = User("John", "Doe")
print(f"{user}")
# John Doe
print(f"{user!r}")
# User's name is: John Doe

We can also just repr (some_var) is called inside the f-string, but using the conversion flag is a good habit and a neat solution.

F-strings outstanding performance

Powerful features and syntactic sugar often come at a performance penalty, but this is not the case with f-strings:

# python -m timeit -s 'x, y = "Hello", "World"' 'f"{x} {y}"'
from string import Template

x, y = "Hello", "World"

print(f"{x} {y}")# 39.6 nsec per loop - Fast!
print(x + " " + y)# 43.5 nsec per loop
print(" ".join((x, y)))# 58.1 nsec per loop
print("%s %s" % (x, y))# 103 nsec per loop
print("{} {}".format(x, y))# 141 nsec per loop
print(Template("$x $y").substitute(x=x, y=y))# 1.24 usec per loop - Slow!

The above example was tested using the timeit following module: python -m timeit -s 'x, y = "Hello", "World" ' 'f"{x} {y}"'As you can see, f-strings are actually the fastest of all the formatting options Python offers. So even if you prefer to use some of the older formatting options, you might consider switching to f-strings just for the improved performance.

Full functionality of formatting specifications

F-strings support Python's Format Specification Mini-Language, so you can add modifiers to them Many formatting operations are embedded in:

text = "hello world"

# Center text:
print(f"{text:^15}")
# 'hello world'

number = 1234567890
# Set separator
print(f"{number:,}")
# 1,234,567,890

number = 123
# Add leading zeros
print(f"{number:08}")
# 00000123

Python's Format Specification Mini-Language includes more than just options for formatting numbers and dates. It allows us to align or center text, add leading zeros/spaces, set thousands separators, and more. All of this obviously applies not only to f-strings, but to all other formatting options.

Nested f-strings

If basic f-strings are not enough for your formatting needs, you can even nest them within each other:

number = 254.3463
print(f"{f'${number:.3f}':>10s}")
# '$254.346'

你可以将 f-strings 嵌入 f-strings 中以解决棘手的格式化问题,例如将美元符号添加到右对齐的浮点数,如上所示。

如果你需要在格式说明符部分使用变量,也可以使用嵌套的 f 字符串。这也可以使 f 字符串更具可读性:

import decimal
width = 8
precision = 3
value = decimal.Decimal("42.12345")
print(f"output: {value:{width}.{precision}}")
# 'output: 42.1'

条件格式

在上面带有嵌套 f 字符串的示例之上,我们可以更进一步,在内部 f 字符串中使用三元条件运算符:

import decimal
value = decimal.Decimal("42.12345")
print(f'Result: {value:{"4.3" if value < 100 else "8.3"}}')
# Result: 42.1
value = decimal.Decimal("142.12345")
print(f'Result: {value:{"4.2" if value < 100 else "8.3"}}')
# Result:142

lambda表达式

如果你想突破 f-strings 的限制,同时让阅读你代码的人觉得你很牛逼,那么你可以使用 lambdas

print(f"{(lambda x: x**2)(3)}")
# 9

在这种情况下,lambda 表达式周围的括号是强制性的,因为:否则将由 f 字符串解释。

结束语

正如我们在这里看到的,f-strings确实非常强大,并且具有比大多数人想象的更多的功能。然而,大多数这些"未知"特性在 Python 文档中都有提及,因此我建议你不仅阅读 f-strings,还阅读你可能使用的任何其他 Python 模块/特性的文档页面。深入研究文档通常会帮助你发现一些非常有用的功能。

The above is the detailed content of Python F-Strings are more powerful than you think. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:51cto.com. If there is any infringement, please contact admin@php.cn delete