Python ascii()

The ascii() method replaces a non-printable character with its corresponding ascii value and returns it.

Example


ascii() Syntax

The syntax of ascii() is:

ascii(object)

ascii() Parameter

The ascii() method takes in a single parameter:

  • object - can be a python list, set, tuple, etc

ascii() Return Value

The ascii() method returns:

  • printable equivalent character for a non-printable character in object

Example 1: Python ascii()

Output

'\u221a represents square root'
'Th\xf6nr is coming'

In the above example, we have used the ascii() method to replace non-printable characters with their corresponding ascii value.

The method replaces:

  • with \u221a in text1
  • ö with \xf6n in text2

Example 2: ascii() with a List

Output

['Python', 'Pyth\xf6\xf1', 5]

In the above example, we have used the ascii() method with a list. The method replaces the non-ascii characters ö with \xf6 and ñ with \xf1.


Example 3: ascii() with a Set

Output

{'\u03b7', '\u03a0', '\u03a6'}

In the above example, we have used the ascii() method with a set.

The method takes the individual non-printable characters in the set as arguments and replaces them with their corresponding ascii values.


Example 4 : ascii() with a Tuple

Output

('\xf6', '\u221a', '\xb6', '\xd0', '\xdf')

Here, we have used the ascii() method with a tuple. The method changes the individual non-printable characters in the tuple to their printable ascii values.


Recommended Readings: