Forcing quote characters in repr(STRING), how?
Duncan Booth
duncan at NOSPAMrcp.co.uk
Thu May 3 08:58:57 EDT 2001
"Tim Peters" <tim.one at home.com> wrote in <mailman.988841104.7613.python-
list at python.org>:
> [François Pinard]
>> When using `repr()' on a string, Python automatically selects if it
>> will use single or double quotes to enclose the produced
>> representation of the string. Is there a clean way to force that
>> choice to be, under user control, a particular quote character
>> (either simple or double)?
>
> Not a clean way, nor even a dirty way: the logic is hardcoded.
>
Never say there isn't a dirty way. The following works, although I really
wouldn't recommend it:
def quote(s, dquote=0):
"""Return repr of the string argument forcing single or double
quotes."""
if dquote:
nasty="'\0"
else:
nasty='"\0'
r = repr(nasty+s)
bad = len(`nasty`)-1
r = r[0]+r[bad:]
return r
if __name__=='__main__':
def test(s):
print "single quote(%s) -> %s" % (`s`, quote(s, 0))
print "double quote(%s) -> %s" % (`s`, quote(s, 1))
test("ab'cd")
test("ab'c\"d")
test('ab"cd')
--
Duncan Booth duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
More information about the Python-list
mailing list