how to determine an 'open' string?

holger krekel pyth at devel.trillke.net
Thu May 16 20:31:10 EDT 2002


John La Rooy wrote:
> bugger ;o)
> we both lose :/
> >>> open_quote('"a"""')
> '"'
> 
> that should be closed, right? or am i misunderstanding the question?

no you are not. it should be closed. i have a fix below.

> if should return anything that *isn't* quoted like
> 
> q('A"quoted bit"B') --> 'AB'

i don't need this variation currently. 

> might need more examples of return values, because "the way python treats quotes"
> doesn't define that for you 

It does. Just enter a string at the interactive prompt and hit
return: if python prints the 'continuation prompt', you are inside a string. 
Note that you can enter e.g. "" "" '' "" """""" """ because python automatically
concatenates these strings (no plus needed). 

So here is the fixed version together with some test cases:

def open_quote(text, rex=re.compile('"""|\'\'\'|"|\'')):
    """ return the open quote at the end of text.
        if all string-quotes are matched, return the
        empty string. thanks to Harvey Thomas&John La Roy.
    """
    rfunc = lambda x,y: x=='' and y  or  not y.startswith(x) and x   or ''
    quotes = rex.findall(text)
    return quotes and reduce(rfunc,quotes) or ''

assert(open_quote(r'''a''')=='')
assert(open_quote(r'''"''')=='"')
assert(open_quote(r'''\'''')=="'")
assert(open_quote(r'''"a"""''')=='')
assert(open_quote(r'''"""a"''')=='"""')
assert(open_quote(r'''"""a""""''')=='"')
assert(open_quote(r'''"""a""""''')=='"')
assert(open_quote(r'''"a"b"a"''')=='')
assert(open_quote(r'''"""''""''"""''')=='')
assert(open_quote(r'''"""''""''"''')=='"""')
assert(open_quote(r'''r"""\"\"\"ad"""''')=='')
assert(open_quote(r'''r""\"ad"""''')=='')
assert(open_quote(r'''r""\""ad"""''')=='"""')

assert('''good night''')

    holger





More information about the Python-list mailing list