ascii() Builtin Function
Python - ascii()
Python ascii() builtin function is used to escape the non-ascii characters in the given object, and return a readable version.
In this tutorial, you will learn the syntax of ascii() function, and then its usage with the help of example programs.
Syntax
The syntax of ascii()
function is
ascii(x)
where
Parameter | Description |
---|---|
x | An object like string, list, tuple, etc. |
Examples
1. 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}')
Output
x : åpple
ascii(x) : '\xe5pple'
Since å
is a non-ascii character, it has been replaces with \xe5
.
2. 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}')
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.