python中字符串格式的演变

String formatting in Python has continuously evolved since its inception. We could always choose the best string formatting based on the use case or prefer to stick to the latest, but its always good to look back from where it all started and revive our memory.

自成立以来,Python中的字符串格式一直在不断发展。 我们总是可以根据用例选择最佳的字符串格式,或者宁愿坚持使用最新的字符串格式,但是从所有起点回顾并恢复我们的记忆始终是一件好事。

Let’s revisit the various string formatting options in Python right from the old school C-style formats to the latest self documenting f-string expressions.

让我们重新讨论Python中的各种字符串格式化选项,从老式的C样式格式到最新的自我记录f字符串表达式。

1.使用%运算符 (1. Using % operator)

Old method of string formatting which uses C-style. This was prevalent before the introduction of Python 3.The % operator is used to format a set of variables in a tuple using the format string. If format requires a single argument, values may be a single non-tuple object.Otherwise, values must be a tuple with exactly the number of items specified by the format string

使用C样式的字符串格式化的旧方法。 这在引入Python 3之前很普遍。%运算符用于使用格式字符串格式化元组中的一组变量。 如果format需要单个参数,则可以是单个非元组对象;否则, 必须是具有格式字符串指定的项目数准确的元组

print("Hello %s" % "programmer")
print("You have %d message" % 1)
print("Hello %s! You have %d message" % ("programmer", 1))Output:Hello programmer
You have 1 message
Hello programmer! You have 1 message

%d and %s are called format specifiers to define the type of argument being printed. These format specifiers hamper the code readability for larger number of arguments.

%d和%s称为格式说明符,用于定义要打印的参数的类型。 这些格式说明符妨碍了更多参数的代码可读性。

2.使用新的字符串格式 (2. Using new string formatting)

This was introduced with Python 3 and then back-ported to Python 2.7.In most of the cases the syntax is similar to the old %-formatting, with the addition of the {} and with : used instead of %. For example, '%03.2f' can be translated to '{:03.2f}'.The new format syntax also supports new and different access options, shown in the following examples.

它是在Python 3中引入的,然后又移植回Python 2.7。在大多数情况下,语法类似于旧的% -formatting,只是增加了{}和with :而不是% 。 例如,可以将'%03.2f'转换为'{:03.2f}' 。新格式的语法还支持新的和不同的访问选项,如以下示例所示。

We can specify arguments in 2 ways.

我们可以通过两种方式指定参数。

  1. By position

    按位置
  2. By name

    按名字
print("Hello {}".format("programmer"))
print("You have {} message".format(1))
print("Hello {}! You have {} message".format("programmer", 1))
print("The value is {:.2f}".format(3.145677888))Output:Hello programmer
You have 1 message
Hello programmer! You have 1 message
The value is 3.15

Accessing arguments by position:

按位置访问参数:

Output:This is an example for new style string formatting 
This is an example for new style string formatting
a comes before b
Hello programmer! You are using python language. You are logged in as programmer

Accessing arguments by name

通过名称访问参数

Output:
The username is programmer. Email : programmer@python.com
The username is programmer. Email : programmer@python.com

In addition to accessing arguments by position and name, we can also access arguments by their items.

除了按位置和名称访问参数外,我们还可以按参数项访问参数。

# accessing dict items using new string formatting
user_info = {"name": "programmer",
"language": "python"}
print("username : {0[name]}, programming in {0[language]} ".format(user_info))Output:
username : programmer, programming in python

The new string.format() is too long again if there are several arguments.

如果有多个参数,则新的string.format()太长。

3.模板字符串 (3. Template Strings)

Template strings provide string substitutions using $ based place holders.Template class has two methods substitute() and safe_substitute() which work similarly except the latter does not throw a key error if the number of arguments are incomplete.

模板字符串使用基于$的占位符提供字符串替换。模板类具有两个方法safe_substitute() substitute()safe_substitute() ,它们的工作原理类似,但是如果参数数量不完整,后者不会引发键错误。

from string import Template
s = "$user is logged in as $role"
t = Template(s)
new_string = t.substitute(user="Programmer", role="administrator")
print(new_string)Output:
Programmer is logged in as administrator

Below code has incomplete set of arguments in the substitute method. This raises a key error.

下面的代码在replace方法中具有不完整的参数集。 这会引发关键错误。

from string import Template
s = "$user is logged in as $role"
t = Template(s)
new_string = t.substitute(user="Programmer")
print(new_string)Output:Traceback (most recent call last):
File "/home/user/MyGitHub/mystring.py", line 38, in <module>
new_string = t.substitute(user="Programmer")
File "/usr/lib/python3.8/string.py", line 126, in substitute
return self.pattern.sub(convert, self.template)
File "/usr/lib/python3.8/string.py", line 119, in convert
return str(mapping[named])
KeyError: 'role'

To handle the above key error we could use safe_substitute().Though this is not quite common its good to know this.

为了解决上述关键错误,我们可以使用safe_substitute()

from string import Template
s = "$user is logged in as $role"
t = Template(s)
new_string = t.safe_substitute(user="Programmer")
print(new_string)Output:
Programmer is logged in as $role

4.字符串插值/ F字符串 (4. String Interpolations/F-Strings)

Introduced in PEP-0498 with Python version 3.6, f-strings provide a way to embed expressions inside string literals, using a minimal syntax. It should be noted that an f-string is really an expression evaluated at run time, not a constant value. In Python source code, an f-string is a literal string, prefixed with ‘f’, which contains expressions inside braces.

f字符串在PEP-0498和Python 3.6版本中引入,它提供了一种使用最小语法将表达式嵌入到字符串文字中的方法。 应该注意的是,f字符串实际上是在运行时评估的表达式,而不是常数。 在Python源代码中,f字符串是文字字符串,前缀为'f',其中包含大括号内的表达式。

As stated in the docs, the f-string evaluates any valid Python expression. Let’s look at examples for all the use cases.

如文档所述,f字符串可评估任何有效的Python表达式。 让我们看一下所有用例的示例。

i. String interpolation for literals

一世。 文字的字符串内插

# This is a string literal
username = "programmer"
role = "admin"
print(f"{username} is logged in as {role}")Output:
programmer is logged in as admin

ii. String interpolation for Python expressions

ii。 Python表达式的字符串插值

# This is an example for string operation
username = "programmer"
role = "admin"
print(f"{username.upper()} is logged in as {role.title()}")Output:
PROGRAMMER is logged in as Admin

Note that we have converted the username to uppercase and role to title case inside the f-string. This is not possible with the other string formatting types.

请注意,我们已经在f字符串中将用户名转换为大写,并将角色转换为标题大写。 对于其他字符串格式类型,这是不可能的。

This will work for mathematical expressions as well.

这也适用于数学表达式。

# This is an example for mathematical expression
n = 2
print(f" The square of {n} is {n*n}")Output:
The square of 2 is 4

5. Python 3.8中f字符串的新增功能 (5. New addition to f-strings in Python 3.8)

From Python 3.8, support for “=” has been added for self documenting expressions to save some typing and for debugging purposes.

从Python 3.8开始,添加了对“ =”的支持,用于自记录表达式以节省一些键入内容并用于调试目的。

response = {"name": "John",
"role": "software engineer"}
print(f" The GET {response=}")Output:
The GET response={'name': 'John', 'role': 'software engineer'}

An f-string expression with = will expand the expression and then evaluate the expression.

带=的f字符串表达式将扩展该表达式,然后评估该表达式。

摘要 (Summary)

  • We have discussed 4 different types of string formatting. Old style, new string formatting, string templates and f-strings

    我们讨论了4种不同类型的字符串格式。 旧样式,新字符串格式,字符串模板和f字符串
  • New string formatting was introduced in Python 3 and back ported to 2.7. This uses str.format() syntax.

    Python 3中引入了新的字符串格式,并将其移植回2.7。 这使用str.format()语法。
  • f-strings are available from Python 3.6 represented by f“{}”

    f字符串可从以f“ {}”表示的Python 3.6中获得
  • f-strings support self documenting expression with “=” from Python 3.8

    f字符串支持Python 3.8中带有“ =”的自我记录表达式

翻译自: https://medium.com/python-in-plain-english/evolution-of-string-formatting-in-python-68e20520076d

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值