Is there any way to make repr(aString) use double quotes?

Fred Gansevles gansevle at ewi.utwente.nl
Tue Apr 8 16:28:31 EDT 2003


Jeremy Fincher wrote:

> The topic really says it all -- I'd like to *force* repr(aString) to
> use double quotes.  Is that possible?
> 
> If it's not, then is it possible to achieve the same thing (everything
> escaped properly, etc.) through other means?
> 
> Thanks,
> Jeremy

the following function does the trick:

def qrepr(s):
     "repr with double-quotes"
     # make one symbol special that isn't treated special in a string, in
     # this case '@'.
     # now modify the string in such a manner that quoting-characters
     # become non-quoting characters, get the repr and reverse the whole
     # operation.
     # replace all '@'-signs with '@@'
     s = s.replace('@', '@@')
     # replace all '"' with '@+@'
     s = s.replace('"', '+ at +')
     # replace all "'" with '@:@')
     s = s.replace("'", '- at -')
     # get the repr
     s = repr(s)[1:-1]
     # and reverse the changes
     s = s.replace('- at -', "'")
     s = s.replace('+ at +', r'\"')
     s = s.replace('@@', '@')
     return '"%s"' % s

if __name__ == '__main__':
    # test
    for s in ('xy', 'x at y', 'x"y', "x'y", 'x@@y', 'x+ at +y', 'x- at -y'):
        print repr(s), qrepr(s)






More information about the Python-list mailing list