ascii() in Python
Last Updated :
08 Feb, 2024
In Python, we have ascii() function that returns a string containing a printable representation of an object. In this article, we will see about ascii() in Python.
Python ascii() Function
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. It’s a built-in function that takes one argument and returns a string that represents the object using only ASCII characters.
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.
Usage of Python ascii() Function
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.
We can use Python ascii() function in the following ways:
- Using ascii() on Python String containing non-ASCII characters
- Python ascii() on new line characters
- Using Python ascii() on Set
- Using Python ascii() on Tuple
- Using Python ascii() on List
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.
Python3
test_str = "G ÃŦ Ê k s f ? r G ? e k s"
print(ascii(test_str))
|
Output
'G \xeb \xea k s f ? r G ? e k s'
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”.
Python3
test_str =
print(ascii(test_str))
|
Output
'Geeks\nfor\ngeeks'
Using Python ascii() on Set
Below example shows how to use Python ascii() on Python Set.
Python3
test_set = {"Å ", "E", "T"}
print("ascii on Python set:", ascii(test_set))
|
Output
ascii on Python set: {'\u0160', 'T', 'E'}
Python ascii() on List
In this example, we are using ascii() on Python List.
Python3
test_list = ["Å", "Ä", "Åī"]
print("ascii on Python list:", ascii(test_list))
|
Output
ascii on Python list: ['\u0147', '\u0115', '\u0174']
Using Python ascii() on Tuple
In this example, we are using Python ascii() on Python Tuple.
Python3
test_tuple = ("ÄĒ", "Ã", "Ã", "D")
print("ascii on Python tuple:", ascii(test_tuple))
|
Output
ascii on Python tuple: ('\u0122', '\xd5', '\xd5', 'D')
Please Login to comment...