string.split escaping

Raymond Hettinger vze4rx4y at verizon.net
Thu May 29 03:45:33 EDT 2003


"Dave Harrison" <dave at nullcube.com> If I have a string
>
> a = 'dog;cat;big;dog'
>
> How do I escape the last ';' so that when I call
>
> string.split(a, ';')
>
> I get
>
> ['dog', 'cat', 'big;dog']

Since the split method doesn't have a builtin escape
mechanism, you'll need to simulate it by:

  * using an escape character of your own choosing
  * use replace() to block out the occurrences in the string
  * do the split
  * use replace() to put back in you split character.

>>> a = 'dog;cat;big_;dog'  # using underscore as an escape character
>>> def mysplit(s, splitchar=';', escchar='_'):
    escaped = escchar + splitchar
    marker = escchar + escchar
    newstr = s.replace(escaped, marker)
    seqn = newstr.split(splitchar)
    return [part.replace(marker, splitchar) for part in seqn]

>>> mysplit(a)
['dog', 'cat', 'big;dog']


Raymond Hettinger






More information about the Python-list mailing list