Triple quoted repr

Denis S. Otkidach ods at strana.ru
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>
DTCT> s = repr("'''multi\n'line'\nstring'''")
DTCT> s = "'''%s'''" % (s[1:-1].replace('\\n',
DTCT> '\n').replace("'''",
DTCT> "\\'\\'\\'"),)
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
'''\'\'\'multi
'line'
string'''''
>>> eval(s)
"'''multi\n'line'\nstring"

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
'''\'\'\'multi
\'line\'
string\'\''''
>>> eval(s)
"'''multi\n'line'\nstring''"

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

-- 
Denis S. Otkidach
http://www.python.ru/      [ru]





More information about the Python-list mailing list