高级字符串格式与模板字符串 [英] advanced string formatting vs template strings

查看:46
本文介绍了高级字符串格式与模板字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道使用模板字符串代替新的高级字符串格式?

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

推荐答案

模板旨在比通常的字符串格式更简单,但要牺牲表达能力.PEP 292 的基本原理将模板与 Python 的 % 进行比较代码>-样式字符串格式:

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:

Python 目前支持基于的字符串替换语法C 的 printf() '%' 格式化字符.虽然很有钱,% 格式的代码也容易出错,即使对于有经验的 Python 程序员.一个常见的错误是离开尾随格式字符,例如%(name)s 中的 s.

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.

此外,可以跟在 % 符号后面的规则是公平的复杂,而通常的应用程序很少需要这样的复杂性.大多数脚本需要做一些字符串插值,但大多数那些使用简单的字符串化"格式,即 %s%(name)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. %s or %(name)s This form should be made simpler and less error prone.

虽然新的 .format() 改善了这种情况,但 格式字符串语法比较复杂,所以道理还是有道理的.

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.

这篇关于高级字符串格式与模板字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆