Python ascii()

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

Example

text = 'Pythön is interesting'

# replace ö with its ascii value print(ascii(text))
# Output: 'Pyth\xf6n is interesting'

ascii() Syntax

The syntax of ascii() is:

ascii(object)

ascii() Parameter

The ascii() method takes in a single parameter:


ascii() Return Value

The ascii() method returns:

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

Example 1: Python ascii()

text1 = '√ represents square root'

# replace √ with ascii value print(ascii(text1))
text2 = 'Thör is coming'
# replace ö with ascii value print(ascii(text2))

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

list = ['Python', 'öñ', 5]

# ascii() with a list print(ascii(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

set = {'Π', 'Φ', 'η'}

// ascii() with a set print(ascii(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

tuple = ('ö', '√', '¶','Ð','ß' )

// ascii() with a tuple print(ascii(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.


Also Read:

Did you find this article helpful?