Forcing quote characters in repr(STRING), how?
Scott David Daniels
daniels at mail.dsl-only.net
Sat Apr 13 02:35:33 EDT 2002
On 12 Apr 2002 21:48:25 -0400, pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) wrote:
..
> 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:])
> [...]
I'd just add a slight tweak tbe a nickel faster:
..
# 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, a NUL,, and a double
# quote -- this not only forces double quotes as delimiters for the
# whole prefixed string, it then follows that with a backslash and
# double quote, forcing the initial cruft to end in a double quote.
# The resulting string will always begin "'\0\"... by dropping the
" "'\0\ part of the repr, we are left with a perfeectly fine repr.
write(repr("'\0\"" + value)[6:])
This saves one string creation.
Isn't fiddling code fun?
-Scott David Daniels
Scott.Daniels at Acm.Org
More information about the Python-list
mailing list