What is the ascii() function in Python?

The ascii() function in Python is used to return a string that is the printable representation of an object. The printable representation of a string contains:

  • The ASCII characterscharacters with ASCII codes from 0-127 of the string are returned as-is.
  • The non-ASCII characterscharacters that cannot be represented by a 7-bit ASCII code are replaced by the escape characters. The escape characters are the hexadecimal representation of the encoded codes of the non-ASCII characters.

Syntax

The ascii() function can be declared as shown in the code snippet below.

ascii(obj)
  • obj: The object whose printable representation is required.

Return value

The ascii() function returns the printable representation of the object obj.

ascii() versus print()

The print() function prints the string on the output stream as it is. On the other hand, the ascii() function escapes the non-ASCII characters.

Example 1

Consider the code snippet below, which demonstrates the use of the ascii() function.

str1 = 'Hêllo wörld!'
print('str1: ', str1)
print('print(str1)', str1)
print('ascii(str1):', ascii(str1))

Explanation

  • We declare a string str1 in line 1.
  • We use the print() function in line 3 to print str1. The print() function simply prints str1 as it is.
  • We use the ascii() function in line 4 to get the printable representation of str1. The non-ASCII character ê is replaced by the escape sequence \xea, which is the hexadecimal representation of its encoded code. Similarly, the non-ASCII character ö is replaced by the escape sequence \xf6.

Example 2

Consider another example of the ascii() method, in which the code returns a printable representation of a list of strings.

lst1 = ['HËllo', 'åpple', 'çomputer']
print('lst1: ', lst1)
print('ascii(lst1):', ascii(lst1))

Explanation

We declare a list of strings lst1 in line 1. We use the ascii() method in line 3, which returns the printable representation of all the members of the list.

Free Resources