Yandex

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'


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M