Python中的可变字符串

Eci*_*ana 34 python string mutable

请问,你知道一个提供可变字符串的Python库吗?谷歌的结果令人惊讶地回归.我找到的唯一可用的库是http://code.google.com/p/gapbuffer/,它在C中,但我更喜欢用纯Python编写.

编辑:感谢您的回复,但我正在追求一个高效的库.也就是说,''.join(list)可能有用,但我希望有更优化的东西.此外,它必须支持常规字符串常用的东西,如正则表达式和unicode.

Jas*_*gan 22

在Python中,可变序列类型是bytearray,请参阅此链接

  • `bytearray`这个名字显然是一个字节数组.字符串不是字节序列,而是字节组的序列.也就是说,这仅适用于ASCII字符串,一般来说不适用于unicode.-1. (12认同)

Joh*_*udd 19

这将允许您有效地更改字符串中的字符.虽然你不能改变字符串长度.

>>> import ctypes

>>> a = 'abcdefghijklmn'
>>> mutable = ctypes.create_string_buffer(a)
>>> mutable[5:10] = ''.join( reversed(list(mutable[5:10].upper())) )
>>> a = mutable.value
>>> print `a, type(a)`
('abcdeJIHGFklmn', <type 'str'>)
Run Code Online (Sandbox Code Playgroud)

  • **警告**缓冲区包含终结符到其报告的`len()`.**除非你为每个负指数添加额外的"-1",否则这将打破带有负数指数的切片**.(对于unicode缓冲区,它也是`-1`,因为这些类型的`len`和slice索引都是字符.) (4认同)

Joe*_*ett 12

class MutableString(object):
    def __init__(self, data):
        self.data = list(data)
    def __repr__(self):
        return "".join(self.data)
    def __setitem__(self, index, value):
        self.data[index] = value
    def __getitem__(self, index):
        if type(index) == slice:
            return "".join(self.data[index])
        return self.data[index]
    def __delitem__(self, index):
        del self.data[index]
    def __add__(self, other):
        self.data.extend(list(other))
    def __len__(self):
        return len(self.data)
Run Code Online (Sandbox Code Playgroud)

... 等等等等.

您还可以继承StringIO,buffer或bytearray.

  • 但是你可以使用正常的字符串.我想/需要利用可变性. (3认同)