[Python-3000] Displaying strings containing unicode escapes

Atsuo Ishimoto ishimoto at gembook.org
Sat May 3 02:54:24 CEST 2008


On Sat, May 3, 2008 at 7:33 AM, Terry Reedy <tjreedy at udel.edu> wrote:
>  so print(s.encode('unicode_escape)) ?
>  Fine with me, especially if that or whatever is added to the repr() doc.
>

I don't recommend repr(obj).encode('unicode_escape'), because
backslash characters in the string will be escaped again by the codec.

>>> print(repr("\\"))
'\\'
>>> print(str(repr("\\").encode("unicode-escape"), "ASCII"))
'\\\\'

'ASCII' codec with 'backslashreplace' error handler works better.

>>> print(str(repr("\\").encode("ASCII", "backslashreplace"), "ASCII"))
'\\'

Looks complicated to get same result as Python 2.x. I originally
proposed to allow print(repr('\\'), encoding="ASCII",
errors="backslashreplace") to get same result, but this is hard to
implement.

If requirement for ASCII-repr is popular enough, we can provide a
built-in function like this:

def repr_ascii(obj):
    return str(repr(obj).encode("ASCII", "backslashreplace"), "ASCII")

2to3 can use repr_ascii() for better compatibility.

Is new built-in function desirable, or just document is good enough?


More information about the Python-3000 mailing list