string processing - some problems whenever I have to parse a more complex string

Ned Batchelder ned at nedbatchelder.com
Tue Oct 21 14:23:22 EDT 2014


On 10/21/14 10:32 AM, CWr wrote:
> Is there any implementation like C++ StringPiece class? Or something like the following behavior:
>
>
>>>> >>>s = StringSlice('abcdef')
>>>> >>>s
> StringSlice('abcdef') at xxx
>>>> >>>s[0]
> 'a'
>>>> >>>s.chop(1) # chop the first item
>>>> >>>s[0] # 'b' is the new first item
> 'b'
>>>> >>>s[:2]
> 'bc'
>>>> >>>s.chop(-1) # chop the last item
>>>> >>>s[-1]
> 'e'
>>>> >>>s[1:]
> 'cde'
>>>> >>>while s[0] != 'e':
>         s.chop(1)
>>>> >>>s[0]
> 'e'
>>>> >>>s.startswith('e')
> True
>>>> >>>s.isdigit()
> False

You could certainly implement a StringSlice object that worked like 
this.  Store the string, the start and end indexes.  Override 
__getitem__ to adjust indexes and slice endpoints, implement chop() to 
change the start or end indexes.  Implementing the string operations 
would get messy, likely you would materialize the sliced string to make 
them work.

-- 
Ned Batchelder, http://nedbatchelder.com




More information about the Python-list mailing list