The Python ascii() function
ascii() is a built-in Python function that returns the ASCII representation of an object.
ascii() It returns a string, similar to repr(), but escapes non-ASCII characters into ASCII characters. This is very useful for debugging and logging.
Word meaning: ascii is short for American Standard Code for Information Interchange.
Basic syntax and parameters
Syntax format
ascii(object)
Parameter Description
- Parameter object:
- Type: any object
- Description: the object whose ASCII representation is wanted.
Function description
- Return Value: returns a string.
- Feature: non-ASCII characters are escaped into the
\x、\uor\Uform.
Example
Example 1: basic usage
Example
A pure ASCII string
s
=
"Hello"
(
ascii
(
s
)
)
Output: 'Hello'
Contains non-ASCII characters
s
=
"Hello" (Chinese)
(
ascii
(
s
)
)
Output: '\xe4\xbd\xa0\xe5\xa5\xbd'
Mixed Chinese and English characters
s
=
"Hello Ni Hao"
(
ascii
(
s
)
)
Output: 'Hello \xe4\xbd\xa0\xe5\xa5\xbd'
Other non-ASCII characters
s
=
"café"
(
ascii
(
s
)
)
Output: 'caf\xc3\xa9'
Expected output:
'Hello'
'\xe4\xbd\xa0\xe5\xa5\xbd'
'Hello \xe4\xbd\xa0\xe5\xa5\xbd'
'caf\xc3\xa9'
Code analysis:
- Pure ASCII characters are left unchanged.
- Non-ASCII characters are escaped.
- Chinese characters use
\xhexadecimal escapes.
Example 2: comparison with repr()
Example
repr vs ascii
s
=
"Chinese"
(
f
"repr: {repr(s)}"
)
Output: repr: 'Chinese'
(
f
"ascii: {ascii(s)}"
)
Output: ascii: '\xe4\xb8\xad\xe6\x96\x87'
List
lst
=
[
"Hello"
,
"Hello" (Chinese)
,
"café"
]
(
repr
(
lst
)
)
Output: ['Hello', 'Ni Hao', 'café']
(
ascii
(
lst
)
)
Output: ['Hello', '\xe4\xbd\xa0\xe5\xa5\xbd', 'caf\xc3\xa9']
Used for printing (to avoid encoding errors)
import
sys
(
ascii
(
"Test"
)
)
Output: '\xe6\xb5\x8b\xe8\xaf\x95'
Expected output:
repr: '中文'
ascii: '\xe4\xb8\xad\xe6\x96\x87'
['Hello', '你好', 'café']
['Hello', '\xe4\xbd\xa0\xe5\xa5\xbd', 'caf\xc3\xa9']
'\xe6\xb5\x8b\xe8\xaf\x95'
ascii() Very useful when non-ASCII characters must be displayed or logged in a pure ASCII environment.
Python3 built-in function