advanced string formatting vs template strings

前端 未结 4 551
南笙
南笙 2020-12-03 02:06

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

4条回答
  •  Happy的楠姐
    2020-12-03 02:46

    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 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.

    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.

提交回复
热议问题