ascii Function in Python – ascii() With Example

In this article, we will learn about ascii function in python – ascii() with example.

Getting Started

ascii() function returns readable version of any object (String, tuple, list etc.). It also replaces any non-ascii character with escape characters.

In other words,
ascii() function replaces non-printable characters of any object with it’s equivalent ASCII characters and returns it.

Syntax of ascii() Function

Syntax of ascii() function –

ascii(object)

Here,
object is any type of object. It can be string, tuple, list etc.

For example,

 
ascii("A B")

Parameter of ascii() Function

As discussed above, ascii function accepts any object i.e. string, tuple, list etc. as parameter.

Return type of ascii() Function

ascii function returns printable equivalent characters of object passed as parameter.

Examples of ascii() Function

Now, we will see how to use ascii() function with different objects –

  1. Using ascii() with List

    ascii() function can be used with python list as shown below –

    list = [1, 2, "öñ", "&"]
    print(ascii(list))
    

    Output:

    [1, 2, '\xf6\xf1', '&']
    

    Here,
    Elements in list are 1, 2, “öñ” and “&”.
    When list is passed as parameter to ascii() function, it returned another list with equivalent ascii characters.

  2. Using ascii() with Set

    ascii() function can be used with python Set as below –

    set1 = {11, 32, "öñ", "å"}
    print(ascii(set1))
    

    Output:

    {32, 11, '\xe5', '\xf6\xf1'}
    

    Here,
    ascii() function converts each item from set into it’s equivalent ascii characters and returns final set.
    Equivalent ASCII character for
    11 is 11
    32 is 32
    “öñ” is ‘\xf6\xf1’
    “å” is ‘\xe5’

    So, we have output as –

    {32, 11, '\xe5', '\xf6\xf1'}
    
  3. Using ascii() with Dictionary

    ascii() function can be used with python Dictionary as below –

    dict = { "key_1" : "öñ", "key_2" : "å"}
    print(ascii(dict))
    

    Output:

    {'key_1': '\xf6\xf1', 'key_2': '\xe5'}
    

    Here,
    Equivalent ASCII character for
    “öñ” is ‘\xf6\xf1’
    “å” is ‘\xe5’
    Equivalent ASCII characters of remaining characters are same.

  4. Using ascii() with Tuple

    ascii() function can be used with python Tuple as below –

    my_tuple = ('1', "å", "öñ")
    print(ascii(my_tuple))
    

    Output:

    ('1', '\xe5', '\xf6\xf1')
    

    Equivalent ASCII character for
    “öñ” is ‘\xf6\xf1’
    “å” is ‘\xe5’

  5. ascii() with String

    ascii() function can be used with python String as below –

    str = "å"
    print(ascii(str))
    

    Output:

    '\xe5'
    

    Here,
    Equivalent ASCII character for
    “å” is ‘\xe5’

Read more at official doc.

Leave a Reply

We are actively looking for Paid Content Writer. Email us at tutorialwing@gmail.com if you are interested.