Python Built-in Function ascii():

The ascii() method is a built-in function in Python that 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.

For example, ASCII code for 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.

Signature

The signature for the ascii() method is as shown below.

ascii(object)

Method parameters and return type

  • Here, The ascii() method takes one type of object parameter.
  • However, it returns a string.

Python Built-in Function ascii Examples:

Example 1: In this example, we take a string where we will give tab and new line both. However, this method returns a printable carriage return character in a string, as shown below.

str='''This	is a tab. This
is a new line'''
print(ascii(str))

Output

'This\tis a tab. This\nis a new line'

Example 2: In this example, We will demonstrate the working of this function with the special symbol “¢”. ASCII value of “¢” is “162” in decimal and “a2” in hexadecimal. So, when we print ascii value of string s it prints “\xa2” which indicates a2 is a hexadecimal value of a symbol.

s="You will be paid ¢5 for this task."
print(ascii(s))
Output
'You will be paid \xa25 for this task.'

Example 3: In this example, let us take a string with multiple lines in it and symbol ¢. Here, we are using symbols as well as newline. Hence, we can see the behaviour of ASCII function vs print function for the same string.

# Initializing
s='''You will be paid ¢5 for this 
task.'''
# Using ascii and print
print(ascii(s))
print(s)

Output

'You will be paid \xa25 for this \ntask.'
You will be paid ¢5 for this 
task.

Conclusion

The ascii() method is used to get the string in its printable representation object. In other words, it prints ascii equivalent of all the symbols and escape sequences.

References

Happy Learning 🙂