Python ascii() Function – Get ASCII Representation of Objects

Python ascii() Function

The ascii() function returns a string that contains a printable representation of an object, but escapes non-ASCII characters using \x, \u, or \U escapes.

It is especially useful when you want to view or debug strings that contain non-English or special characters.

Syntax

ascii(object)

Parameter:

  • object – Any Python object (commonly a string or list)

Returns:

  • A string that contains the ASCII-only representation of the object
  • All non-ASCII characters are escaped

Example 1: ASCII of a string with special characters

text = "café"
print(ascii(text))
'caf\xe9'

Here, the accented character é is escaped as \xe9.

Example 2: ASCII of emojis or symbols

print(ascii("Python 🐍"))
'Python \U0001f40d'

Example 3: ASCII of a list with strings

names = ["José", "Zoë", "Müller"]
print(ascii(names))
['Jos\xe9', 'Zo\xeb', 'M\xfcller']

ascii() vs repr()

The repr() function returns a string representation, but keeps non-ASCII characters as-is if possible. In contrast, ascii() always escapes them.

print(repr("café"))   # 'café'
print(ascii("café"))  # 'caf\xe9'

Use Cases of ascii()

  • Debugging strings with special/non-English characters
  • Serializing or logging readable representations of objects
  • Ensuring output contains only ASCII-safe text

Common Mistakes

  • Confusing ascii() with ord() – they are different
  • ascii() does not encode or convert characters; it only escapes them for safe viewing

Interview Tip

Know the difference between str(), repr(), and ascii(). Interviewers often ask about string representation functions and how they behave with special characters.

Summary

  • ascii() returns a printable representation of an object
  • Escapes all non-ASCII characters using escape codes
  • Useful for debugging and safe printing/logging

Practice Problem

Try printing ASCII-safe versions of the following:

words = ["niño", "français", "中文"]
for word in words:
    print(ascii(word))

Expected Output:

'ni\xf1o'
'fran\xe7ais'
'\u4e2d\u6587'