Forcing quote characters in repr(STRING), how?
François Pinard
pinard at iro.umontreal.ca
Fri Apr 12 21:48:25 EDT 2002
Hi! Cleaning old mail, I stumbled on that old conversation:
---------------------------------------------------------------------->
[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)?
[Tim Peters]
> Not a clean way, nor even a dirty way: the logic is hardcoded.
[Duncan Booth]
> 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')
----------------------------------------------------------------------<
Despite not recommended, I nevertheless followed the trick above in Pymacs.
Preceded by a long comment, the little piece of code looks almost clean :-).
[...]
elif type(value) == types.StringType:
# Python delimits a string it by single quotes preferably, unless
# single quotes appear within the string while double quotes do
# not, in which case it uses double quotes for string delimiters.
# Checking the string contents, the C code stops at the first NUL.
# We prefix the string with a single quote and a NUL, this forces
# double quotes as delimiters for the whole prefixed string. Then,
# we get rid of the representation of the single quote and the NUL.
write('"' + repr("'\0" + value)[6:])
[...]
--
François Pinard http://www.iro.umontreal.ca/~pinard
More information about the Python-list
mailing list