Python ascii() function takes an object (like a string) and returns a printable representation of it. It converts any non-ASCII characters into escape sequences (like \u
followed by the Unicode code point), making it safe to use in situations where only ASCII characters are allowed.
ascii()
Syntax
result = ascii(object)
result
: Stores the ASCII-safe string representation.ascii()
: The built-in Python function for conversion.object
: The object (string, list, etc.) you want to make ASCII-safe.
Example 1: Python ascii()
text = "Café" # Contains a non-ASCII character (é)
ascii_text = ascii(text)
print(ascii_text)
Code Explanation
- Line 1: Assigns a string with a non-ASCII character to the
text
variable - Line 2: The
ascii()
function converts the non-ASCII character ‘é’ into its escape sequence ‘\xe9’ - Line 3: Prints the ASCII-safe representation
Output
‘Caf\xe9’
Example 2: Python ascii()
with List
my_list = ["apple", "piña", "banana"]
ascii_list = ascii(my_list)
print(ascii_list) # Output: ['apple', 'pi\xf1a', 'banana']
Code Explanation
- Line 1: A list containing strings, one with a non-ASCII character
- Line 2:
ascii()
processes each element in the list, converting non-ASCII characters - Line 3: Prints the ASCII-safe representation of the list
Output
[‘apple’, ‘pi\xf1a’, ‘banana’]
Example 3: Python ascii()
with Set
my_set = {"café", "tea", "latte"}
ascii_set = ascii(my_set)
print(ascii_set)
Code Explanation
- Line 1: A set containing strings, one with a non-ASCII character
- Line 2:
ascii()
converts non-ASCII characters within the set elements - Line 3: Prints the ASCII-safe representation, note that sets are unordered
Output
{‘tea’, ‘caf\xe9’, ‘latte’}
Example 4: Python ascii()
with Tuple
my_tuple = ("hello", "world", "olé!")
ascii_tuple = ascii(my_tuple)
print(ascii_tuple)
Code Explanation
- Line 1: A tuple with strings, one containing a non-ASCII character
- Line 2:
ascii()
handles the non-ASCII character within the tuple - Line 3: Prints the ASCII-safe version of the tuple
Output
(‘hello’, ‘world’, ‘ol\xe9!’)