Triple quoted repr

Denis S. Otkidach ods at
Thu Jun 3 11:23:05 CEST 2004

On Thu, 3 Jun 2004, Delaney, Timothy C (Timothy) wrote:

DTCT> >  > I need a way of writing strings or arbitrary Python
DTCT> code that will
DTCT> >  >
DTCT> >  > a) allow the strings to be read again unchanged (like
DTCT> repr)
DTCT> >  > b) write multiline strings as multiline strings
DTCT> instead of escaping
DTCT> >  > the \n's.
DTCT> Perhaps something like:
DTCT> s = repr("'''multi\n'line'\nstring'''")
DTCT> s = "'''%s'''" % (s[1:-1].replace('\\n',
DTCT> '\n').replace("'''",
DTCT> "\\'\\'\\'"),)
DTCT> which changes \n to a linefeed, \r to a carriage return,
DTCT> and ''' to an
DTCT> escaped form (in case you have a triple-quoted string with
DTCT> the same
DTCT> quote character).

This fails for some strings, e.g.:
>>> s = repr("'''multi\n'line'\nstring''")
>>> s = "'''%s'''" % (s[1:-1].replace('\\n', '\n').replace("'''", "\\'\\'\\'"),)
>>> print s
>>> eval(s)

A better solution:
>>> def trepr(s):
...     return "'''"+'\n'.join([`l+'"'`[1:-2] for l in s.split('\n')])+"'''"
>>> s = trepr("'''multi\n'line'\nstring''")
>>> print s
>>> eval(s)

Or you can improve your solution to handle quotes properly at the
begining and the end of string.

Denis S. Otkidach      [ru]

More information about the Python-list mailing list