Triple quoted repr

Duncan Booth me at privacy.net
Thu Jun 3 03:58:26 EDT 2004


"Delaney, Timothy C (Timothy)" <tdelaney at avaya.com> wrote in 
news:mailman.529.1086233144.6949.python-list at python.org:

>> There were no responses. Anyone have an answer?
> 
> Perhaps something like:
> 
> s = repr("'''multi\n'line'\nstring'''")
> s = "'''%s'''" % (s[1:-1].replace('\\n', '\n').replace("'''",
> "\\'\\'\\'"),)
> 
> which changes \n to a linefeed, \r to a carriage return, and ''' to an
> escaped form (in case you have a triple-quoted string with the same
> quote character).

That doesn't work very well if you have escaped backslashes followed by 
'n':

>>> s = '\\n'
>>> print "'''%s'''" % (s[1:-1].replace('\\n', '\n').replace("'''",
"\\'\\'\\'"),)
''''''

Try this instead:

def trepr(s):
    text = '\n'.join([repr(line)[1:-1] for line in s.split('\n')])
    quotes, dquotes = "'''", '"""'
    if quotes in text:
        if dquotes in text:
            text = text.replace(quotes, "\\'\\'\\'")
        else:
            quotes = dquotes
    return "%s%s%s" % (quotes, text, quotes)

It isn't perfect (lines with both ' and " will escape the single quote), 
but it is pretty close.



More information about the Python-list mailing list