Skip to content
Related Articles
Open in App
Not now

Related Articles

ascii() in Python

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 25 Jul, 2022
Improve Article
Save Article

Python ascii() function returns a string containing a printable representation of an object and escapes the non-ASCII characters in the string using \x, \u or \U escapes.

Python ascii() Function Syntax

Syntax: ascii(object)

  • object: Any Python object (ex.: string, int, list, tuple, set, etc.)

Returns: Returns a string as a printable representation of the object passed, escaping the non-ASCII characters.

The method can take only one parameter, an object that can be a list, strings, etc. As already discussed, it returns a printable representation of an object.

Python ascii() function Example

We see that in these examples, all the non-ASCII characters have been escaped, i.e, their encoded code gets displayed by using the ascii() method.





Example 1: Using ascii() on Python String containing non-ASCII characters

In this example, test_str variable contains not-ASCII character and our task is to display its ASCII value from the given string.


# Python program to illustrate ascii()
test_str = "G ë ê k s f ? r G ? e k s"


'G \xeb \xea k s f ? r G ? e k s'

Example 2: Python ascii() on new line characters

Here we take a variable with multiline string and pass it into the ascii() and it returns “\n”, the value of new line is “\n”.


test_str = '''Geeks



Example 3: Using Python ascii() on Set, List & Tuple

Below example shows how to use Python ascii() on Python Set, List and Tuple.


# Python ascii() on Set
test_set = {"Š", "E", "T"}
print("ascii on Python set:", ascii(test_set))
# Python ascii() on List
test_list = ["Ň", "ĕ", "Ŵ"]
print("ascii on Python list:", ascii(test_list))
# Python ascii() on Tuple
test_tuple = ("Ģ", "Õ", "Õ", "D")
print("ascii on Python tuple:", ascii(test_tuple))


ascii on Python set: {'\u0160', 'T', 'E'}
ascii on Python list: ['\u0147', '\u0115', '\u0174']
ascii on Python tuple: ('\u0122', '\xd5', '\xd5', 'D')

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!