高级字符串格式与模板字符串

时间:2021-01-15 18:05:55

I was wondering if there is a advantage of using template strings instead of the new advanced string formatting?

我想知道使用模板字符串而不是新的高级字符串格式是否有优势?

4 个解决方案

#1


17  

Templates are meant to be simpler than the the usual string formatting, at the cost of expressiveness. The rationale of PEP 292 compares templates to Python's %-style string formatting:

模板意味着比通常的字符串格式更简单,代价是表达性。 PEP 292的基本原理将模板与Python的%样式字符串格式进行比较:

Python currently supports a string substitution syntax based on C's printf() '%' formatting character. While quite rich, %-formatting codes are also error prone, even for experienced Python programmers. A common mistake is to leave off the trailing format character, e.g. the s in %(name)s.

Python目前支持基于C的printf()'%'格式化字符的字符串替换语法。虽然非常丰富,但%格式化代码也容易出错,即使对于有经验的Python程序员也是如此。一个常见的错误是不要使用尾随格式字符,例如%(名称)s中的s。

In addition, the rules for what can follow a % sign are fairly complex, while the usual application rarely needs such complexity. Most scripts need to do some string interpolation, but most of those use simple stringification' formats, i.e.%sor%(name)s` This form should be made simpler and less error prone.

此外,可以遵循%符号的规则相当复杂,而通常的应用程序很少需要这样的复杂性。大多数脚本需要进行一些字符串插值,但大多数脚本使用简单的字符串化格式,即%sor%(name)s`这种形式应该更简单,更不容易出错。

While the new .format() improved the situation, it's still true that the format string syntax is rather complex, so the rationale still has its points.

虽然新的.format()改善了这种情况,但格式字符串语法仍然相当复杂,所以理由仍然有其重点。

#2


9  

For what it's worth, Template substitution from a dict appears to be 4 to 10 times slower than format substitution, depending on the length of the template. Here's a quick comparison I ran under OS X on a 2.3 GHz core i7 with Python 3.5.

对于它的价值,来自dict的模板替换似乎比格式替换慢4到10倍,具体取决于模板的长度。这是我在OS X上使用Python 3.5在2.3 GHz核心i7上运行的快速比较。

from string import Template
lorem = "Lorem ipsum dolor sit amet {GIBBERISH}, consectetur adipiscing elit {DRIVEL}. Expectoque quid ad id, quod quaerebam, respondeas."
loremtpl = Template("Lorem ipsum dolor sit amet $GIBBERISH, consectetur adipiscing elit $DRIVEL. Expectoque quid ad id, quod quaerebam, respondeas.")
d = dict(GIBBERISH='FOOBAR', DRIVEL = 'RAXOOP')

In [29]: timeit lorem.format(**d)
1.07 µs ± 2.13 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [30]: timeit loremtpl.substitute(d)
8.74 µs ± 12.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

The worst case I tested was about 10 times slower for a 13 character string. The best case I tested was about 4 times slower for a 71000 character string.

我测试的最糟糕的情况是13字符串慢了大约10倍。我测试的最好的情况是71000字符串慢了大约4倍。

#3


5  

One key advantage of string templates is that you can substitute only some of the placeholders using the safe_substitute method. Normal format strings will raise an error if a placeholder is not passed a value. For example:

字符串模板的一个关键优势是您可以使用safe_substitute方法仅替换部分占位符。如果占位符未传递值,则正常格式字符串将引发错误。例如:

"Hello, {first} {last}".format(first='Joe')

raises:

提出:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'last'

But:

但:

from string import Template
Template("Hello, $first $last").safe_substitute(first='Joe')

Produces:

生产:

'Hello, Joe $last'

Note that the returned value is a string, not a Template; if you want to substitute the $last you'll need to create a new Template object from that string.

请注意,返回的值是字符串,而不是模板;如果你想用$ last替换你需要从该字符串创建一个新的Template对象。

#4


2  

Its primarily a matter of syntax preference, which usually boils down to a laziness/verbosity tradeoff and familiarity/habits with existing string template systems. In this case template strings are more lazy/simple/quick to write, while .format() is more verbose and feature-full.

它主要是语法偏好的问题,通常归结为现有字符串模板系统的懒惰/冗长权衡和熟悉/习惯。在这种情况下,模板字符串更加懒惰/简单/快速编写,而.format()更详细,功能更丰富。

Programmers used to the PHP language or the Jinja family of template systems may prefer template strings. Using "%s" positional style tuple substitution might appeal to those who use printf-like string formatting or want something quick. .format() has a few more features, but unless you need something specific that only .format() provides, there is nothing wrong with using any existing scheme.

习惯于PHP语言或Jinja系列模板系统的程序员可能更喜欢模板字符串。使用“%s”位置样式元组替换可能会吸引那些使用类似printf的字符串格式或想要快速的东西。 .format()还有一些功能,但除非你需要特定的东西,只有.format()提供,否则使用任何现有的方案都没有错。

The only thing to be aware of is that named string templates are more flexible and require less maintenance than order-dependent ones. Other than that it all comes down to either personal preference or the coding standard of the project you are working on;

唯一需要注意的是,命名字符串模板比依赖于顺序的字符串模板更灵活,所需维护更少。除此之外,这一切都归结为个人偏好或您正在进行的项目的编码标准;

#1


17  

Templates are meant to be simpler than the the usual string formatting, at the cost of expressiveness. The rationale of PEP 292 compares templates to Python's %-style string formatting:

模板意味着比通常的字符串格式更简单,代价是表达性。 PEP 292的基本原理将模板与Python的%样式字符串格式进行比较:

Python currently supports a string substitution syntax based on C's printf() '%' formatting character. While quite rich, %-formatting codes are also error prone, even for experienced Python programmers. A common mistake is to leave off the trailing format character, e.g. the s in %(name)s.

Python目前支持基于C的printf()'%'格式化字符的字符串替换语法。虽然非常丰富,但%格式化代码也容易出错,即使对于有经验的Python程序员也是如此。一个常见的错误是不要使用尾随格式字符,例如%(名称)s中的s。

In addition, the rules for what can follow a % sign are fairly complex, while the usual application rarely needs such complexity. Most scripts need to do some string interpolation, but most of those use simple stringification' formats, i.e.%sor%(name)s` This form should be made simpler and less error prone.

此外,可以遵循%符号的规则相当复杂,而通常的应用程序很少需要这样的复杂性。大多数脚本需要进行一些字符串插值,但大多数脚本使用简单的字符串化格式,即%sor%(name)s`这种形式应该更简单,更不容易出错。

While the new .format() improved the situation, it's still true that the format string syntax is rather complex, so the rationale still has its points.

虽然新的.format()改善了这种情况,但格式字符串语法仍然相当复杂,所以理由仍然有其重点。

#2


9  

For what it's worth, Template substitution from a dict appears to be 4 to 10 times slower than format substitution, depending on the length of the template. Here's a quick comparison I ran under OS X on a 2.3 GHz core i7 with Python 3.5.

对于它的价值,来自dict的模板替换似乎比格式替换慢4到10倍,具体取决于模板的长度。这是我在OS X上使用Python 3.5在2.3 GHz核心i7上运行的快速比较。

from string import Template
lorem = "Lorem ipsum dolor sit amet {GIBBERISH}, consectetur adipiscing elit {DRIVEL}. Expectoque quid ad id, quod quaerebam, respondeas."
loremtpl = Template("Lorem ipsum dolor sit amet $GIBBERISH, consectetur adipiscing elit $DRIVEL. Expectoque quid ad id, quod quaerebam, respondeas.")
d = dict(GIBBERISH='FOOBAR', DRIVEL = 'RAXOOP')

In [29]: timeit lorem.format(**d)
1.07 µs ± 2.13 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [30]: timeit loremtpl.substitute(d)
8.74 µs ± 12.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

The worst case I tested was about 10 times slower for a 13 character string. The best case I tested was about 4 times slower for a 71000 character string.

我测试的最糟糕的情况是13字符串慢了大约10倍。我测试的最好的情况是71000字符串慢了大约4倍。

#3


5  

One key advantage of string templates is that you can substitute only some of the placeholders using the safe_substitute method. Normal format strings will raise an error if a placeholder is not passed a value. For example:

字符串模板的一个关键优势是您可以使用safe_substitute方法仅替换部分占位符。如果占位符未传递值,则正常格式字符串将引发错误。例如:

"Hello, {first} {last}".format(first='Joe')

raises:

提出:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'last'

But:

但:

from string import Template
Template("Hello, $first $last").safe_substitute(first='Joe')

Produces:

生产:

'Hello, Joe $last'

Note that the returned value is a string, not a Template; if you want to substitute the $last you'll need to create a new Template object from that string.

请注意,返回的值是字符串,而不是模板;如果你想用$ last替换你需要从该字符串创建一个新的Template对象。

#4


2  

Its primarily a matter of syntax preference, which usually boils down to a laziness/verbosity tradeoff and familiarity/habits with existing string template systems. In this case template strings are more lazy/simple/quick to write, while .format() is more verbose and feature-full.

它主要是语法偏好的问题,通常归结为现有字符串模板系统的懒惰/冗长权衡和熟悉/习惯。在这种情况下,模板字符串更加懒惰/简单/快速编写,而.format()更详细,功能更丰富。

Programmers used to the PHP language or the Jinja family of template systems may prefer template strings. Using "%s" positional style tuple substitution might appeal to those who use printf-like string formatting or want something quick. .format() has a few more features, but unless you need something specific that only .format() provides, there is nothing wrong with using any existing scheme.

习惯于PHP语言或Jinja系列模板系统的程序员可能更喜欢模板字符串。使用“%s”位置样式元组替换可能会吸引那些使用类似printf的字符串格式或想要快速的东西。 .format()还有一些功能,但除非你需要特定的东西,只有.format()提供,否则使用任何现有的方案都没有错。

The only thing to be aware of is that named string templates are more flexible and require less maintenance than order-dependent ones. Other than that it all comes down to either personal preference or the coding standard of the project you are working on;

唯一需要注意的是,命名字符串模板比依赖于顺序的字符串模板更灵活,所需维护更少。除此之外,这一切都归结为个人偏好或您正在进行的项目的编码标准;