Skip to content

Python ascii() Function


The ascii() function in Python returns a printable representation of an object. It escapes non-ASCII characters using escape sequences like \x, \u, or \U depending on the character.

Here are a few examples to demonstrate the ascii() function

Example 1: Working with Strings

text = "Hello, this is a non-ASCII character: é"
print(ascii(text))

Output:

'Hello, this is a non-ASCII character: \xe9'

In this example, the ascii() function represents the non-ASCII character ‘é’ using its hexadecimal escape sequence \xe9.

Example 2: Working with Non-String Objects

num = 123
print(ascii(num))

list_items = [1, 'apple', 'orange', 'π']
print(ascii(list_items))

Output:

123
[1, 'apple', 'orange', '\u03c0']
  • For an integer (num), the ascii() function returns the same integer without any escape sequence because integers don’t contain non-ASCII characters.
  • For the list (list_items), it represents the non-ASCII character ‘π’ using its Unicode escape sequence \u03c0.

The ascii() function is mainly used for debugging or displaying representations of objects in a way that is suitable for code interpretation or debugging, especially when dealing with non-ASCII characters or characters that need escaping for various purposes.

Comments are closed, but trackbacks and pingbacks are open.