How To Use Python ascii() Function With Examples

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.

  1. The ascii() function in Python returns a string containing a printable representation of an object.
  2. It escapes non-ASCII characters using Unicode escape sequences \uXXXX and \UXXXXXXXX, and backslashes are escaped with a backslash.
  3. This function can be useful for debugging and printing non-ASCII strings in a readable format.

2. Python ascii() Function Syntax.

  1. Here is the syntax for the ascii() function.
    ascii(object)
  2. The object argument is any object such as a string, number, list, tuple, set, or dictionary.

3. Python ascii() Function Examples.

  1. Here are some examples of using the ascii() function in Python.
  2. 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!
  3. 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!'
  4. 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'}
  5. 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', 'Привет', 'Мир']
  6. Example 5: Convert special character (©) to ascii code in a string.
    >>> string = "hello world! ©"
    >>>
    >>> print(ascii(string))
    'hello world! \xa9'

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.