Python ascii()

Python ascii() builtin function takes an object as argument and returns a string. The string contains printable representation of the given object. Any non-ASCII characters in the resulting string will be escaped.

In this tutorial, we will learn about the syntax of Python ascii() function, and learn how to use this function with the help of examples.

Syntax

The syntax of ascii() function with object as parameter is

</>
Copy
ascii(object)

where

ParameterRequired/OptionalDescription
objectRequiredA Python object like string, list, tuple, etc.

Returns

The function returns string.

Examples

1. ascii() with no arguments

In this example, we will take a list and get the printable string using ascii() builtin function.

Python Program

</>
Copy
myList = ['apple', 'banana']
result = ascii(myList)
print(f'Return Value: {result}')

Output

Return Value: ['apple', 'banana']

2. ascii() with Non-ASCII Characters

In this example, we will take a string with non-ascii characters and get the printable string using ascii() builtin function.

Python Program

</>
Copy
myBytes = b'\x65\x99\x00\n\x25'
result = ascii(myBytes)
print(f'Return Value: {result}')

Output

Return Value: b'e\x99\x00\n%'

Conclusion

In this Python Tutorial, we have learnt the syntax of Python ascii() builtin function, and also learned how to use this function, with the help of Python example programs.