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()
function can be declared as shown in the code snippet below.
ascii(obj)
obj
: The object whose printable representation is required.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.
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))
str1
in line 1.print()
function in line 3 to print str1
. The print()
function simply prints str1
as it is.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
.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))
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.