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

发布于 2024-08-12 00:12:05 字数 250 浏览 1 评论 0原文

字符串格式化表达式:

'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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

水水月牙 2024-08-19 00:12:05

两者都不;第一个在很多地方都有使用,第二个是刚刚介绍的。所以问题更多的是你喜欢哪种风格。我实际上更喜欢基于 dict 的格式:

d = { 'count': 1, 'txt': 'nice' }
'This is %(count)d %(txt)s example!' % d

它确保正确的参数进入正确的位置,允许在多个位置重用相同的参数等。

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:

d = { 'count': 1, 'txt': 'nice' }
'This is %(count)d %(txt)s example!' % d

It makes sure that the right parameter goes into the right place, allows to reuse the same parameter in several places, etc.

痕至 2024-08-19 00:12:05

我想我读到 % 运算符在 3.1 中已被弃用,所以我坚持使用 format() 函数。

请参阅 PEP 3101:字符串格式化的新方法

I thought I read that the % operator is being deprecated in 3.1 already, so I'd stick with the format() function.

See PEP 3101: A New Approach To String Formatting

清音悠歌 2024-08-19 00:12:05

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

PEP 3101:
新系统不会与现有字符串格式化技术的任何方法名称发生冲突,因此两个系统可以共存,直到弃用旧系统为止。

这个想法仍在追求中:

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

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

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

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.

The idea is still being pursued:

We are still encouraging people to use the new str.format().
Python Issue 7343

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文