为了账号安全,请及时绑定邮箱和手机立即绑定

哪个是在Python中连接字符串的首选方法?

哪个是在Python中连接字符串的首选方法?

四季花海 2019-07-25 19:15:28
哪个是在Python中连接字符串的首选方法?由于Python string无法更改,我想知道如何更有效地连接字符串?我可以这样写:s += stringfromelsewhere或者像这样:s = []s.append(somestring)later s = ''.join(s)在写这个问题时,我发现了一篇很好的文章谈论这个话题。http://www.skymind.com/~ocrow/python_string/但它是在Python 2.x.中,所以问题是在Python 3中做了哪些改变?
查看完整描述

3 回答

?
30秒到达战场

TA贡献1828条经验 获得超6个赞

如果你连接很多值,那么两者都没有。附加清单很昂贵。您可以使用StringIO。特别是如果你在很多操作中构建它。

from cStringIO import StringIO# python3:  from io import StringIObuf = StringIO()buf.write('foo')buf.write('foo')buf.write('foo')buf.getvalue()# 'foofoofoo'

如果您已经从其他操作返回了完整列表,那么只需使用 ''.join(aList)

来自python FAQ:将多个字符串连接在一起的最有效方法是什么?

str和bytes对象是不可变的,因此将多个字符串连接在一起效率很低,因为每个连接都会创建一个新对象。在一般情况下,总运行时间成本是总字符串长度的二次方。

要累积许多str对象,推荐的习惯用法是将它们放入一个列表中并在结尾处调用str.join():

chunks = []for s in my_strings:
    chunks.append(s)result = ''.join(chunks)

(另一个合理有效的习惯是使用io.StringIO)

要累积许多字节对象,推荐的习惯用法是使用就地连接(+ =运算符)扩展bytearray对象:

result = bytearray()for b in my_bytes_objects:
    result += b

编辑:我是愚蠢的,并将结果向后粘贴,使其看起来像是附加到列表比cStringIO更快。我还添加了对bytearray / str concat的测试,以及使用带有更大字符串的更大列表的第二轮测试。(python 2.7.3)

用于大型字符串列表的ipython测试示例

try:

    from cStringIO import StringIO

except:

    from io import StringIO


source = ['foo']*1000


%%timeit buf = StringIO()

for i in source:

    buf.write(i)

final = buf.getvalue()

# 1000 loops, best of 3: 1.27 ms per loop


%%timeit out = []

for i in source:

    out.append(i)

final = ''.join(out)

# 1000 loops, best of 3: 9.89 ms per loop


%%timeit out = bytearray()

for i in source:

    out += i

# 10000 loops, best of 3: 98.5 µs per loop


%%timeit out = ""

for i in source:

    out += i

# 10000 loops, best of 3: 161 µs per loop


## Repeat the tests with a larger list, containing

## strings that are bigger than the small string caching 

## done by the Python

source = ['foo']*1000


# cStringIO

# 10 loops, best of 3: 19.2 ms per loop


# list append and join

# 100 loops, best of 3: 144 ms per loop


# bytearray() +=

# 100 loops, best of 3: 3.8 ms per loop


# str() +=

# 100 loops, best of 3: 5.11 ms per loop


查看完整回答
反对 回复 2019-07-25
?
慕桂英546537

TA贡献1848条经验 获得超10个赞

在Python> = 3.6中,新的f-string是连接字符串的有效方法。

>>> name = 'some_name'>>> number = 123>>>>>> f'Name is {name} and the number is {number}.''Name is some_name and the number is 123.'


查看完整回答
反对 回复 2019-07-25
  • 3 回答
  • 0 关注
  • 521 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信