ascii() Builtin Function

Python – ascii()

Python ascii() builtin function escapes the non-ascii characters in the given object, and returns a readable version.

Syntax

The syntax of ascii() function is

ascii(x)

where x is an object like string, list, tuple, etc.

Examples

Escape non-ascii in string

In the following program, we take a string in x, and escape any non-ascii characters if present in it.

Python Program

x = "åpple"
output = ascii(x)
print(f'x        : {x}')
print(f'ascii(x) : {output}')
Run

Output

x        : åpple
ascii(x) : '\xe5pple'

Since å is a non-ascii character, it has been replaces with \xe5.

Escape non-ascii in list

In the following program, we take a list of strings containing non-ascii characters, and escape them using ascii() function.

Python Program

x = ["åpple", "日本人"]
output = ascii(x)
print(f'x        : {x}')
print(f'ascii(x) : {output}')
Run

Output

x        : ['åpple', '日本人']
ascii(x) : ['\xe5pple', '\u65e5\u672c\u4eba']

Summary

In this tutorial of Python Examples, we learned the syntax of ascii() function, and how to escape non-ascii characters in the given object using ascii() with examples.