gpt4 book ai didi

python - 高级字符串格式化与模板字符串

转载 作者:IT老高 更新时间:2023-10-28 21:33:40 26 4
gpt4 key购买 nike

我想知道使用 template strings 是否有优势而不是新的advanced 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.

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() 改善了这种情况,但 format string syntax 仍然是事实。比较复杂,所以原理还是有道理的。

关于python - 高级字符串格式化与模板字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11630106/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com