The
ascii()
function in Python is used to represent a string or any other Python object using only ASCII characters. This can be useful when dealing with non-ASCII characters that may not be supported by all systems or applications. In this article, I will tell you the syntax of python ascii() function and how to use it with some examples.
1. Python ascii() Function Introduction.
- The
ascii()
function in Python returns a string containing a printable representation of an object. - It escapes non-ASCII characters using Unicode escape sequences
\uXXXX
and\UXXXXXXXX
, and backslashes are escaped with a backslash. - This function can be useful for debugging and printing non-ASCII strings in a readable format.
2. Python ascii() Function Syntax.
- Here is the syntax for the
ascii()
function.ascii(object)
- The
object
argument is any object such as a string, number, list, tuple, set, or dictionary.
3. Python ascii() Function Examples.
- Here are some examples of using the
ascii()
function in Python. - Example 1: Print a string with non-ASCII characters.
>>> my_string = "Héllo, Wörld!" >>> >>> print(my_string) # output the none ascii characters ( é, ö ) as it is. Héllo, Wörld!
- Example 2: Print a string with non-ASCII characters using the
ascii()
function.>>> my_string = "Héllo, Wörld!" >>> >>> print(ascii(my_string)) # the ascii() function convert the non-ascii character (é, ö) to it's ascii signs. 'H\xe9llo, W\xf6rld!'
- Example 3: Print a dictionary with non-ASCII keys and values.
>>> my_dict = {"Héllo": "Wörld", "Привет": "Мир"} >>> >>> print(ascii(my_dict)) {'H\xe9llo': 'W\xf6rld', '\u041f\u0440\u0438\u0432\u0435\u0442': '\u041c\u0438\u0440'}
- Example 4: Print a list with non-ASCII strings.
>>> my_list = ["Héllo", "Wörld", "Привет", "Мир"] >>> >>> print(ascii(my_list)) ['H\xe9llo', 'W\xf6rld', '\u041f\u0440\u0438\u0432\u0435\u0442', '\u041c\u0438\u0440'] >>> >>> print(my_list) ['Héllo', 'Wörld', 'Привет', 'Мир']
- Example 5: Convert special character (©) to ascii code in a string.
>>> string = "hello world! ©" >>> >>> print(ascii(string)) 'hello world! \xa9'