Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 ascii() Function

The Python ascii() function

Python3 Built-in Functions Python3 built-in 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

- Type: any object - Description: the object whose ASCII representation is wanted.

Function description


Example

Example 1: basic usage

Example

A pure ASCII string

s

=

"Hello"

print

(

ascii

(

s

)

)

 

Output: 'Hello'

Contains non-ASCII characters

s

=

"Hello" (Chinese)

print

(

ascii

(

s

)

)

 

Output: '\xe4\xbd\xa0\xe5\xa5\xbd'

Mixed Chinese and English characters

s

=

"Hello Ni Hao"

print

(

ascii

(

s

)

)

 

Output: 'Hello \xe4\xbd\xa0\xe5\xa5\xbd'

Other non-ASCII characters

s

=

"café"

print

(

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:

  1. Pure ASCII characters are left unchanged.
  2. Non-ASCII characters are escaped.
  3. Chinese characters use \x hexadecimal escapes.

Example 2: comparison with repr()

Example

repr vs ascii

s

=

"Chinese"

print

(

f

"repr: {repr(s)}"

)

 

Output: repr: 'Chinese'

print

(

f

"ascii: {ascii(s)}"

)

Output: ascii: '\xe4\xb8\xad\xe6\x96\x87'

List

lst

=

[

"Hello"

,

"Hello" (Chinese)

,

"café"

]

print

(

repr

(

lst

)

)

 

Output: ['Hello', 'Ni Hao', 'café']

print

(

ascii

(

lst

)

)

 

Output: ['Hello', '\xe4\xbd\xa0\xe5\xa5\xbd', 'caf\xc3\xa9']

Used for printing (to avoid encoding errors)

import

sys

print

(

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 Functions Python3 built-in function