Python ascii() 函数
ascii() 是 Python 中用于返回对象的 ASCII 表示的内置函数。
ascii() 返回一个字符串,类似于 repr(),但它会将非 ASCII 字符转义为 ASCII 字符。这对于调试和日志记录非常有用。
单词释义: ascii 是 American Standard Code for Information Interchange(美国信息交换标准代码)的缩写。
基本语法与参数
语法格式
ascii(object)
参数说明
- 参数 object:
- 类型: 任意对象
- 描述: 要获取 ASCII 表示的对象。
函数说明
- 返回值: 返回一个字符串。
- 特点: 非 ASCII 字符会被转义为
\x、\u或\U形式。
实例
示例 1:基础用法
实例
# 纯 ASCII 字符串
s = "Hello"
print(ascii(s)) # 输出: 'Hello'
# 包含非 ASCII 字符
s = "你好"
print(ascii(s)) # 输出: '\xe4\xbd\xa0\xe5\xa5\xbd'
# 中文和英文字符混合
s = "Hello 你好"
print(ascii(s)) # 输出: 'Hello \xe4\xbd\xa0\xe5\xa5\xbd'
# 其他非 ASCII 字符
s = "café"
print(ascii(s)) # 输出: 'caf\xc3\xa9'
s = "Hello"
print(ascii(s)) # 输出: 'Hello'
# 包含非 ASCII 字符
s = "你好"
print(ascii(s)) # 输出: '\xe4\xbd\xa0\xe5\xa5\xbd'
# 中文和英文字符混合
s = "Hello 你好"
print(ascii(s)) # 输出: 'Hello \xe4\xbd\xa0\xe5\xa5\xbd'
# 其他非 ASCII 字符
s = "café"
print(ascii(s)) # 输出: 'caf\xc3\xa9'
运行结果预期:
'Hello' '\xe4\xbd\xa0\xe5\xa5\xbd' 'Hello \xe4\xbd\xa0\xe5\xa5\xbd' 'caf\xc3\xa9'
代码解析:
- 纯 ASCII 字符保持不变。
- 非 ASCII 字符会被转义。
- 中文字符使用
\x十六进制转义。
示例 2:与 repr() 对比
实例
# repr vs ascii
s = "中文"
print(f"repr: {repr(s)}") # 输出: repr: '中文'
print(f"ascii: {ascii(s)}") # 输出: ascii: '\xe4\xb8\xad\xe6\x96\x87'
# 列表
lst = ["Hello", "你好", "café"]
print(repr(lst)) # 输出: ['Hello', '你好', 'café']
print(ascii(lst)) # 输出: ['Hello', '\xe4\xbd\xa0\xe5\xa5\xbd', 'caf\xc3\xa9']
# 用于打印(避免编码错误)
import sys
print(ascii("测试")) # 输出: '\xe6\xb5\x8b\xe8\xaf\x95'
s = "中文"
print(f"repr: {repr(s)}") # 输出: repr: '中文'
print(f"ascii: {ascii(s)}") # 输出: ascii: '\xe4\xb8\xad\xe6\x96\x87'
# 列表
lst = ["Hello", "你好", "café"]
print(repr(lst)) # 输出: ['Hello', '你好', 'café']
print(ascii(lst)) # 输出: ['Hello', '\xe4\xbd\xa0\xe5\xa5\xbd', 'caf\xc3\xa9']
# 用于打印(避免编码错误)
import sys
print(ascii("测试")) # 输出: '\xe6\xb5\x8b\xe8\xaf\x95'
运行结果预期:
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() 对于需要在纯 ASCII 环境中显示或记录非 ASCII 字符非常有用。

Python3 内置函数