字符串格式化表达式 (Python)
字符串格式化表达式:
'This is %d %s example!' % (1, 'nice')
字符串格式化方法调用:
'This is {0} {1} example!'.format(1, 'nice')
为了可读性,我个人更喜欢方法调用(第二个示例),但由于它是新的,随着时间的推移,其中一个或另一个可能会被弃用。您认为哪个不太可能被弃用?
String formatting expressions:
'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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
两者都不;第一个在很多地方都有使用,第二个是刚刚介绍的。所以问题更多的是你喜欢哪种风格。我实际上更喜欢基于
dict
的格式:它确保正确的参数进入正确的位置,允许在多个位置重用相同的参数等。
Neither; the first one is used in a lot of places and the second one was just introduced. So the question is more which style you prefer. I actually prefer the
dict
based formatting:It makes sure that the right parameter goes into the right place, allows to reuse the same parameter in several places, etc.
我想我读到
%
运算符在 3.1 中已被弃用,所以我坚持使用format()
函数。请参阅 PEP 3101:字符串格式化的新方法
I thought I read that the
%
operator is being deprecated in 3.1 already, so I'd stick with theformat()
function.See PEP 3101: A New Approach To String Formatting
最初的想法是逐渐切换到 str.format() 方法,同时允许两种方式:
这个想法仍在追求中:
由于最初的 '%' 方法计划在 2019 年的某个时候被弃用和删除未来,我建议使用 str.format() 编写新代码。尽管目前这只是个人喜好问题。我个人更喜欢使用基于字典的格式,'%' 运算符和 str.format() 方法都支持这种格式。
The original idea was to gradually switch to str.format() approach while allowing both ways:
The idea is still being pursued:
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.