Python ascii() Function
ascii()Is a built-in function in Python used to return the ASCII representation of an object.
ascii()Returns a string, similar torepr(), but it escapes non-ASCII characters as ASCII characters. This is very useful for debugging and logging.
Term Definition: asciiIs the abbreviation 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 to be obtained.
Function Description
- Return value: Returns a string.
- Feature: Non-ASCII characters are escaped as
\x、\uor\Uform.
Examples
Example 1: Basic Usage
Example
# Pure ASCII string
s = "Hello"
print(ascii(s)) # Output: 'Hello'
# Contains non-ASCII characters
s = Hello
print(ascii(s)) # Output: '\xe4\xbd\xa0\xe5\xa5\xbd'
# Mixed Chinese and English characters
s = Hello Hello
print(ascii(s)) # Output: 'Hello \xe4\xbd\xa0\xe5\xa5\xbd'
# Other non-ASCII characters
s = "café"
print(ascii(s)) # Output: 'caf\xc3\xa9'
s = "Hello"
print(ascii(s)) # Output: 'Hello'
# Contains non-ASCII characters
s = Hello
print(ascii(s)) # Output: '\xe4\xbd\xa0\xe5\xa5\xbd'
# Mixed Chinese and English characters
s = Hello Hello
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:
- Pure ASCII characters remain unchanged.
- Non-ASCII characters are escaped.
- Chinese characters use
\xhexadecimal escaping.
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, "café"]
print(repr(lst)) # Output: ['Hello', 'Hello', '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'
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, "café"]
print(repr(lst)) # Output: ['Hello', 'Hello', '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()It is very useful when you need to display or record non-ASCII characters in a pure ASCII environment.
Other Extensions
Python3 Built-in Functions