Python equivalent of Java StringBuffer?

后端 未结 8 1296
半阙折子戏
半阙折子戏 2020-12-04 21:10

Is there anything in Python like Java\'s StringBuffer? Since strings are immutable in Python too, editing them in loops would be inefficient.

8条回答
  •  南方客
    南方客 (楼主)
    2020-12-04 21:27

    Perhaps use a bytearray:

    In [1]: s = bytearray('Hello World')
    
    In [2]: s[:5] = 'Bye'
    
    In [3]: s
    Out[3]: bytearray(b'Bye World')
    
    In [4]: str(s)
    Out[4]: 'Bye World'
    

    The appeal of using a bytearray is its memory-efficiency and convenient syntax. It can also be faster than using a temporary list:

    In [36]: %timeit s = list('Hello World'*1000); s[5500:6000] = 'Bye'; s = ''.join(s)
    1000 loops, best of 3: 256 µs per loop
    
    In [37]: %timeit s = bytearray('Hello World'*1000); s[5500:6000] = 'Bye'; str(s)
    100000 loops, best of 3: 2.39 µs per loop
    

    Note that much of the difference in speed is attributable to the creation of the container:

    In [32]: %timeit s = list('Hello World'*1000)
    10000 loops, best of 3: 115 µs per loop
    
    In [33]: %timeit s = bytearray('Hello World'*1000)
    1000000 loops, best of 3: 1.13 µs per loop
    

提交回复
热议问题