The ascii() function:
Syntax of using ascii function
The syntax of using the ascii function is simple:
An example of using a string object in ascii function
In this example, normal text is used in the ascii function. After this example, I will show you how to use non-ASCII characters:
The code and output:
#A demo of ascii function an_str = 'simple text' print(ascii(an_str))
The result:
Using non-ascii characters in a string
Now see the output as I used the non-ASCII character in a string object and used it in the ascii() function. First, I used the copyright sign and this is followed by using the registered sign:
str_non = 'copyright = ©' print(ascii(str_non))
The output:
Similarly,
str_non = 'Registered sign = ®' print(ascii(str_non))
The output:
So, How ascii function works?
Basically, the ascii() function works by encoding the output of repr() function to use escape sequences for any codepoint in the output produced by repr() function that is not within the ASCII range.
In Python 2:
print repr("®")
The result:
In Python 3:
print(repr("®"))
The output:
However, as we have seen in the above example, the ascii() produced the following:
print(ascii("®"))
The output:
Now, let us look at another example of using the ascii() function.
An example of using a list object in ascii function
A list with a few elements is created. The string elements also include Latin-1 characters (non-ASCII) along with normal characters. See the code and its result:
#A demo of ascii with a list a_List = ['©', 'á', 'µ' ,'bé' ,'pound' ,'£'] print(ascii(a_List))
The result: