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
of the string are returned as-is.ASCII characters characters with ASCII codes from 0-127 - The
are replaced by the escape characters. The escape characters are the hexadecimal representation of the encoded codes of the non-ASCII characters.non-ASCII characters characters that cannot be represented by a 7-bit ASCII code
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
str1in line 1. - We use the
print()function in line 3 to printstr1. Theprint()function simply printsstr1as it is. - We use the
ascii()function in line 4 to get the printable representation ofstr1. 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.