Quote aware split

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue May 15 23:18:49 EDT 2007


En Tue, 15 May 2007 21:50:15 -0300, Ondrej Baudys <obaudys at gmail.com>  
escribió:

> After trawling through the archives for a simple quote aware split
> implementation (ie string.split-alike that only splits outside of
> matching quote) and coming up short,  I implemented a quick and dirty
> function that suits my purposes.

Just a small comment:

> def qsplit(chars, sep, quote="'"):
>     """ Quote aware split """
>     qcount = 0
>     splitpoints = [-1] # ie. seperator char found before first letter ;)
>     for index, c in enumerate(chars):
>         if c is quote:
>             qcount += 1
>         if c is sep and qcount % 2 == 0:
>             splitpoints.append(index)

The "is" operator checks object *identity*, that is, if both operands are  
actually the same object. It may or may not work here, depending on many  
implementation details. You really should check if they are *equal*  
instead:

          if c == quote:
              qcount += 1
          if c == sep and qcount % 2 == 0:
              splitpoints.append(index)

See:
py> x='a'
py> y='A'.lower()
py> y
'a'
py> x==y
True
py> x is y
False

-- 
Gabriel Genellina




More information about the Python-list mailing list