To learn about the ascii()
function in Python, first, let's see some examples of ASCII and non-ASCII characters.
What are ASCII and non-ASCII characters?
- A capital "T" is represented by 84.
- A lowercase "a" is represented by 97.
- The escape key(ESC) is represented by 27.
Definition of ascii()
ascii()
method is a built-in Python function that replaces any non-ASCII characters with escape characters(\x, \u or \U escapes). This method returns a string containing a readable and printable representation of an object(String, Tuple, List, Dictionary, etc.)- ö changes to \xf6n
- √ changes to \u221a.
Syntax of ascii()
ascii(object)
The ascii()
method accepts an object like String, List, Tuple, Dictionary, etc. as a parameter.
Return value of ascii()
ascii()
method is always a String type.print(type(ascii([])))
<class 'str'>
So, now, after getting to know the basic definition of the ascii()
method and its syntax, let's go through some examples to see its implementation.
How the ascii() method works?
Example:
print(ascii("ê"))
'\xea'
print(ascii("й"))
'\u0439'
print(ascii("µ"))
'\xb5'
ascii()
method.ascii()
method:Examples:
Example 1: String as a Parameter
# A normal string
str1 = "This is a plain text"
print(ascii(str1))
# A string containing non-ascii character
str2= 'Ä ballöon is in the air'
print(ascii(str2))
# To display a string having non-ASCII character value using print()
print('P\xa5thon is inter\xeasting')
'This is a plain text'
'\xc4 ball\xf6on is in the air'
P¥thon is interêsting
In the above example, we have two strings, str1
and str2
.
str1
is a plain text with no non-ASCII characters and str2
contains two non-ASCII characters(Ä, ö).
As we can see in the output, the non-ASCII character is replaced with a readable representation of the non-ASCII character:
Ä is changed to \xc4
ö is changed to \xf6
The bottom print() statement prints the non-ASCII characters of their respective encoded value:
\xa5 is changed to ¥
\xea is changed to ê
Example 2: List as a Parameter
myList = ['Librar¥', 'Böök']
print(ascii(myList))
['Librar\xa5', 'B\xf6\xf6k']
Here, we have a List, myList
of two elements passed as a parameter to the ascii()
method.
ö is changed to \xf6
¥ is changed to \xa5
Example 3: Tuple as a Parameter
myTuple = ('√9','√16', '√25')
print(ascii(myTuple))
['\u221a9', '\u221a16', '\u221a25']
Here, we have a Tuple, myTuple
of three elements passed as a parameter to the ascii()
method.
√ is changed to \u221a