gpt4 book ai didi

python - python += 字符串连接是不好的做法吗?

转载 作者:IT老高 更新时间:2023-10-28 22:15:04 25 4
gpt4 key购买 nike

我正在阅读 The Hitchhiker’s Guide to Python并且有一个简短的代码片段

foo = 'foo'
bar = 'bar'

foobar = foo + bar # This is good
foo += 'ooo' # This is bad, instead you should do:
foo = ''.join([foo, 'ooo'])

作者指出''.join()并不总是比+快,所以他并不反对使用+字符串连接。

但是为什么 foo += 'ooo' 是不好的做法,而 foobar=foo+bar 被认为是好的?

  • foo += bar好吗?
  • foo = foo + 'ooo' 好吗?

在这段代码之前,作者写道:

One final thing to mention about strings is that using join() is not always best. In the instances where you are creating a new string from a pre-determined number of strings, using the addition operator is actually faster, but in cases like above or in cases where you are adding to an existing string, using join() should be your preferred method.

最佳答案

这是不好的做法吗?

可以合理地假设这个例子不是坏习惯,因为:

  • 作者没有给出任何理由。也许只是他/她不喜欢。
  • Python 文档没有提到这是不好的做法(据我所知)。
  • foo += 'ooo'foo = ''.join([foo, 'ooo']) 一样具有可读性(根据我的说法)并且大约快 100 倍.

什么时候应该使用一个而不是另一个?

字符串连接的缺点是需要为每个连接创建一个新字符串并分配新的内存!这很耗时,但对于很少和很小的字符串来说并不是什么大问题。当您知道要连接的字符串数量并且不需要超过 2-4 个连接时,我会选择它。


当连接字符串时,Python 只需为最终的字符串分配新内存,这样效率更高,但计算时间可能更长。此外,由于字符串是不可变的,因此使用字符串列表进行动态变异通常更实用,并且仅在需要时将其转换为字符串。

使用 str.join() 创建字符串通常很方便,因为它需要一个可迭代对象。例如:

letters = ", ".join("abcdefghij")

总结

在大多数情况下,使用 str.join() 更有意义,但有时串联同样可行。在我看来,对大字符串或多字符串使用任何形式的字符串连接都是不好的做法,就像使用 str.join() 对短字符串和少数字符串来说是不好的做法一样。

我相信作者只是想创建一个经验法则,以便更容易地确定何时使用什么,而不需要过多的细节或使它变得复杂。

关于python - python += 字符串连接是不好的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39675898/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com