字符串格式化表达式(Python) [英] String formatting expressions (Python)

查看:122
本文介绍了字符串格式化表达式(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.

这篇关于字符串格式化表达式(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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