Python ascii() Method
ASCII stands for American Standard Code for Information Interchange. It is a character encoding standard that uses numbers from 0 to 127 to represent English characters. For example, ASCII code for the character A is 65, and 90 is for Z. Similarly, ASCII code 97 is for a, and 122 is for z. ASCII codes are also used to represent characters such as tab, form feed, carriage return, and also some symbols.
The ascii()
method in Python returns a string containing a printable representation of an object for non-alphabets or invisible characters such as tab, carriage return, form feed, etc. It escapes the non-ASCII characters in the string using \x
, \u
or \U
escapes.
Syntax:
ascii(object)
Parameters:
object: Any type of object.
Return type:
Returns a string.
The ascii()
method returns a printable carriage return character in a string, as shown below.
mystr='''this
is a new line.'''
print(ascii(mystr))
'this\nis a new line.'
In the above example, mystr
points to a string with a carriage return, which takes a string in the new line. It is an invisible character in the string. The ascii()
method returns a printable string that converts a carriage return to printable char \n. Please note that it does not convert other English characters.
The following example prints symbol Ø using the ascii()
method:
NormalText = "A string in python."
SpecialText = "A string in pythØn."
print(ascii(NormalText))
print(ascii(SpecialText))
'A string in python.'
'A string in pyth\xd8n.'
In the above example, ASCII code for Ø is decimal 216, and hexadecimal D8, which is represented using \x prefix, \xd8. So, the ascii()
method converts Ø to \xd8 in a string.
It escapes the non-ASCII characters in the string using \x
, \u
or \U
escapes.
The following demonstrates the ascii()
method with lists.
Languages = ['pythØn','C++','Go']
print(ascii(Languages))
['pyth\xd8n', 'C++', 'Go']
ascii() vs print()
The following example demonstrates the difference between the ascii()
and print() function.
print(ascii('PythØn'))
print('Pyth\xd8n')
Pyth\xd8n
PythØn