字符串格式化表达式(Python)

问题描述:

字符串格式表达式:

'This is %d %s example!' % (1, 'nice')

字符串格式化方法调用:

String formatting method calls:

'This is {0} {1} example!'.format(1, 'nice')

我个人更喜欢方法调用(第二个示例),以提高可读性,但是由于它是新的,因此随着时间的推移,其中一个或另一个可能会被弃用。您认为哪一个不太可能被弃用?

I personally prefer the method calls (second example) for readability but since it is new, there is some chance that one or the other of these may become deprecated over time. Which do you think is less likely to be deprecated?

最初的想法是逐渐切换到str.format()方法同时允许两种方式:

The original idea was to gradually switch to str.format() approach while allowing both ways:


PEP 3101:

新系统不会与任何方法名称冲突现有字符串格式化技术的一种,因此这两种系统可以共存,直到需要弃用旧系统为止。

PEP 3101:
The new system does not collide with any of the method names of the existing string formatting techniques, so both systems can co-exist until it comes time to deprecate the older system.

这个想法仍在追寻:


我们仍在鼓励人们使用新的str.format()。
Python问题7343

由于计划在将来的某个时候弃用和删除原始的%方法,因此建议使用str.format()编写新代码。尽管目前,这只是个人喜好问题。我个人更喜欢使用基于字典的格式,'%'运算符和str.format()方法都支持这种格式。

Since the original '%' approach is planned to be deprecated and removed at some point in the future, I would suggest writing new code with str.format(). Though at the moment, it is just a matter of personal preference. I personally prefer using dictionary-based formatting, which is supported by both '%' operator and str.format() method.