Skip to main content

ascii()

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

Parameter Values

Parameter Description
object

The object (string, bytes, or bytearray) to be checked for ASCII representation.

Return Values

The ascii() function always returns a str representing a printable string.

How to Use ascii() in Python

Example 1:

The ascii() function returns a string containing a printable representation of an object, with escape sequences for non-ASCII characters.

obj = 'hèllö' 
print(ascii(obj)) # Output: 'h\xe8ll\xf6'
Example 2:

It can be used with non-string objects like integers as well.

num = 128541 
print(ascii(num)) # Output: 128541
Example 3:

When applied to a list, it provides the string representation of the list with escape sequences.

my_list = [1, 'hello', 'π'] 
print(ascii(my_list)) # Output: [1, 'hello', '\u03c0']