有什么理由不使用“+"来连接两个字符串? [英] Any reason not to use '+' to concatenate two strings?

查看:66
本文介绍了有什么理由不使用“+"来连接两个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 中一个常见的反模式是在循环中使用 + 连接字符串序列.这很糟糕,因为 Python 解释器必须为每次迭代创建一个新的字符串对象,并且最终需要二次时间.(最近版本的 CPython 显然可以在某些情况下优化这一点,但其他实现却不能,因此不鼓励程序员依赖它.)''.join 是做到这一点的正确方法.

A common antipattern in Python is to concatenate a sequence of strings using + in a loop. This is bad because the Python interpreter has to create a new string object for each iteration, and it ends up taking quadratic time. (Recent versions of CPython can apparently optimize this in some cases, but other implementations can't, so programmers are discouraged from relying on this.) ''.join is the right way to do this.

但是,我听说过(包括 Stack Overflow 上的此处)您应该永远,永远使用 + 进行字符串连接,而是始终使用 ''.join 或格式字符串.如果您只连接两个字符串,我不明白为什么会出现这种情况.如果我的理解是正确的,它不应该花费二次时间,而且我认为 a + b''.join((a, b)) 更清晰,更易读code> 或 '%s%s' % (a, b).

However, I've heard it said (including here on Stack Overflow) that you should never, ever use + for string concatenation, but instead always use ''.join or a format string. I don't understand why this is the case if you're only concatenating two strings. If my understanding is correct, it shouldn't take quadratic time, and I think a + b is cleaner and more readable than either ''.join((a, b)) or '%s%s' % (a, b).

使用 + 连接两个字符串是个好习惯吗?还是有我不知道的问题?

Is it good practice to use + to concatenate two strings? Or is there a problem I'm not aware of?

推荐答案

+ 连接 两个 字符串没有错.实际上它比 ''.join([a, b]) 更容易阅读.

There is nothing wrong in concatenating two strings with +. Indeed it's easier to read than ''.join([a, b]).

你是对的,虽然用 + 连接 2 个以上的字符串是一个 O(n^2) 操作(与 join 的 O(n) 相比),因此变得低效.然而,这与使用循环无关.即使 a + b + c + ... 也是 O(n^2),原因是每次连接都会产生一个新字符串.

You are right though that concatenating more than 2 strings with + is an O(n^2) operation (compared to O(n) for join) and thus becomes inefficient. However this has not to do with using a loop. Even a + b + c + ... is O(n^2), the reason being that each concatenation produces a new string.

CPython2.4 及更高版本尝试减轻这种情况,但在连接超过 2 个字符串时仍然建议使用 join.

CPython2.4 and above try to mitigate that, but it's still advisable to use join when concatenating more than 2 strings.

这篇关于有什么理由不使用“+"来连接两个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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