Is there any way to make repr(aString) use double quotes?
gansevle at ewi.utwente.nl
Tue Apr 8 22:28:31 CEST 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?
the following function does the trick:
"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
# 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__':
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