Python ascii() Method

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

python ascii()

Python ascii() Syntax

ascii( object )

The ascii() method takes an object like lists, strings etc as the parameter.

As we already mentioned, ascii() method returns the printable version of a string escaping the non-ASCII character using \x, \u or \U escapes.

ascii() and repr()

Earlier in Python2, repr() method was used to return the printable representation of an object but it didn’t escape the non-ASCII characters.

For example, ë is represented as ë by repr()  method, but by ascii() method, it is represented by Python escape sequence \xeb. Similarly, ö is represented as ö by repr() and \xf6n by ascii() method.

Here is an example code.

>>> print(repr('ë')) 
'ë' 
>>> print(ascii('ë')) 
'\xeb'

Python ascii() Method Example

>>> str1 = 'Python Unicode'
>>> print(ascii(str1)) 
'Python Programming'

>>> str2 = 'Pythön Unicödë'
>>> print(ascii(str2))
'Pyth\xf6nn Unic\xf6nd\xeb'

As you can see in above script, ö is represented by escape sequence \xf6n and ë by \xeb when used with Python ascii() method.