Skip to content
Tutorials Center
My learning

Topics

Python Reference · Built-in Functions

Python ascii() function

Reference for Python ascii(): get a printable representation of any object with non-ASCII characters escaped, and how it differs from repr() and str().

The built-in ascii() function returns a string containing a printable representation of an object, like repr(), but with every non-ASCII character replaced by an escape sequence (\xe9, 日, \U0001f600). The result can be safely shown in a terminal, log file or protocol that only handles ASCII.

Only the representation is escaped. The object itself is not changed, and because the output is a string you will see quote characters around text values.

Python
ascii("café")    # "'caf\\xe9'"

Try it

Python Escaping non-ASCII characters

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python ascii() on your own class

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
ascii(object)
Name Description
object Any object.

Return value: a str. Python calls repr(object) and then escapes every non-ASCII character with \x, \u or \U escapes.

Raises: nothing special; errors raised by the object's __repr__() propagate.

Usage notes

  • Escapes are chosen by size. Code points up to 0xFF use \xNN, up to 0xFFFF use \uNNNN, and larger ones use \UNNNNNNNN.
  • Same as !a. In f-strings and str.format(), the conversion !a calls ascii(), just as !r calls repr() and !s calls str().
  • Not an encoder. ascii() returns text, not bytes. To get bytes use str.encode("ascii", errors="backslashreplace"), which produces similar escapes.
  • Valid Python source. The escaped text can be evaluated again, so eval(ascii(x)) rebuilds simple values such as strings and lists.
  • Useful for debugging text. It makes invisible and look-alike characters (non-breaking spaces, accented letters, zero-width characters) visible.
  • Quotes remain. ascii("hi") is "'hi'" (a string that contains quotes). Use print(ascii(...)) to see it without the outer layer.
  • No effect on ASCII text. Plain ASCII content gives the same result as repr().