46

変更可能な文字列を提供する Python ライブラリを知っていますか? Google は驚くほど少ない結果を返しました。私が見つけた唯一の使用可能なライブラリはhttp://code.google.com/p/gapbuffer/で、これは C で書かれていますが、純粋な Python で書かれたほうがよいと思います。

編集:返信ありがとうございますが、私は効率的なライブラリを求めています。つまり、''.join(list)うまくいくかもしれませんが、もっと最適化されたものを望んでいました。また、正規表現やユニコードなど、通常の文字列が行う通常のものをサポートする必要があります。

4

7 に答える 7

28

Python の可変シーケンス タイプはbytearrayで、このリンクを参照してください

于 2012-05-13T15:01:07.877 に答える
22

これにより、文字列内の文字を効率的に変更できます。ただし、文字列の長さは変更できません。

>>> 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'>)
于 2014-10-03T02:14:49.260 に答える
15
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)

...などなど。

StringIO、buffer、または bytearray をサブクラス化することもできます。

于 2012-05-13T15:06:55.190 に答える