The ascii() function is a built-in function in Python that returns a string that contains a printable version of an object. It escapes non-ASCII characters using backslash escapes and returns a string that can be used to represent the object in ASCII format.
Here's an example of using ascii() with a string that contains non-ASCII characters:
|
string = "Héllo Wórld"
print(ascii(string)) # 'H\xe9llo W\xf3rld'
|
In this example, we define a string that contains non-ASCII characters. When we call ascii() on the string, it returns a string that contains the ASCII representation of the original string. The non-ASCII characters are escaped using backslash escapes.
ascii() is often used to escape non-ASCII characters in a string so that it can be safely represented in ASCII format. It can also be used with other objects, such as lists and dictionaries. Here's an example:
|
my_list = [1, 2, "Héllo", "Wórld", {"key": "value"}]
print(ascii(my_list))
# '[1, 2, \'H\\xe9llo\', \'W\\xf3rld\', {\'key\': \'value\'}]'
|