Вопрос по python, string – Изменчивые строки в Python

28

Error: User Rate Limit Exceededhttp://code.google.com/p/gapbuffer/ который находится в C, но я бы предпочел, чтобы он был написан на чистом Python.

Изменить: Спасибо за ответы, но я послеefficientError: User Rate Limit Exceeded''.join(list) может сработать, но я надеялся на что-то более оптимизированное. Кроме того, он должен поддерживать обычные вещи, которые делают обычные строки, такие как регулярные выражения и юникод.

Error: User Rate Limit Exceeded Aaron Yodaiken
Error: User Rate Limit Exceeded Zaur Nasibov
Error: User Rate Limit ExceededLINK1, LINK2 digEmAll
Error: User Rate Limit Exceeded chuwy
Error: User Rate Limit Exceeded Zaur Nasibov

Ваш Ответ

4   ответа
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)

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceededre.match(expression, repr(mutable_string))
Error: User Rate Limit ExceededfindError: User Rate Limit ExceededstrError: User Rate Limit Exceededobject.
Error: User Rate Limit Exceeded
Error: User Rate Limit ExceededfindError: User Rate Limit Exceeded__setitem__Error: User Rate Limit Exceeded
18

>>> 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'>)
BE WARNEDError: User Rate Limit Exceededlen(). This will break slices with negative indicesError: User Rate Limit Exceeded-1Error: User Rate Limit Exceeded-1Error: User Rate Limit Exceededlen и индексы срезов для этих типов в символах.)
2

list

class CharList(list):

    def __init__(self, s):
        list.__init__(self, s)

    @property
    def list(self):
        return list(self)

    @property
    def string(self):
        return "".join(self)

    def __setitem__(self, key, value):
        if isinstance(key, int) and len(value) != 1:
            cls = type(self).__name__
            raise ValueError("attempt to assign sequence of size {} to {} item of size 1".format(len(value), cls))
        super(CharList, self).__setitem__(key, value)

    def __str__(self):
        return self.string

    def __repr__(self):
        cls = type(self).__name__
        return "{}(\'{}\')".format(cls, self.string)

s = "te_st"
c = CharList(s)
c[1:3] = "oa"
c += "er"
print c # prints "toaster"
print c.list # prints ['t', 'o', 'a', 's', 't', 'e', 'r']

There's one (solvable) caveat: There's no check (yet) that each element is indeed a character. It will at least fail printing for everything but strings. However, those can be joined and may cause weird situations like this: [see code example below]

__setitem__ValueErrorTypeError: sequence item n: expected string, X foundstring.join()__setslice__collections.Sequence)

s = "test"
c = CharList(s)
c[1] = "oa"
# with custom __setitem__ a ValueError is raised here!
# without custom __setitem__, we could go on:
c += "er"
print c # prints "toaster"
# this looks right until here, but:
print c.list # prints ['t', 'oa', 's', 't', 'e', 'r']
21

bytearray

Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded

Похожие вопросы