how to determine an 'open' string?

Sean 'Shaleh' Perry shalehperry at attbi.com
Thu May 16 12:05:06 EDT 2002


>> 
>> Seems a really simple solution is count the number of each type of quote in
>> the
>> string.  But first you need to find all of the triple quotes.
> 
> i thought along those lines, too, but couldn't get it correct easily. 
> 
>> for each quote type:
>>   count = find all triple quotes
>>   if count is even: closed
> 
> for
>     """''' askldjl'''
> 
> this returns 'closed': wrong!
> 

right, you need to handle ", then '.

import re

test_string = '"""\'\'\' askldjl\'\'\''

STATE_OPEN = 0
STATE_CLOSED = 1
state = STATE_OPEN

dblqt_triple = re.compile(r'(""")')
snglqt_triple = re.compile(r"(''')")

m = dblqt_triple.search(test_string)
count = len(m.groups())
if count == 0 or (count % 2) == 0:
  state = STATE_CLOSED
new_string = dblqt_triple.sub('', test_string)

m = snglqt_triple.search(new_string)
count = len(m.groups())
if count == 0 or (count % 2) == 0:
  state = STATE_CLOSED
new_string = snglqt_triple.sub('', new_string)

and a similar pattern for checking normal quotes.





More information about the Python-list mailing list