如何获取控制字符的Unicode值?Python中ASCII控制字符操作方法
关于控制字符Unicode值及Python获取方法的解答
控制字符的Unicode值
ASCII控制字符的Unicode值与它们的ASCII码完全一致,因为Unicode直接兼容ASCII编码,所有ASCII控制字符在Unicode中对应的码点就是其原始ASCII数值。
Python中获取ASCII控制字符并使用ord()的方法
有几种简单方式可以获取这些控制字符,再传入ord()得到对应数值:
1. 使用转义序列
Python支持直接用转义字符表示常见控制字符,示例如下:
# 获取NUL(空字符)的Unicode值 print(ord('\0')) # 输出: 0 # 获取DEL(删除字符)的Unicode值 print(ord('\x7f')) # 输出: 127 # 获取CR(回车)的Unicode值 print(ord('\r')) # 输出: 13 # 获取LF(换行)的Unicode值 print(ord('\n')) # 输出: 10 # 获取BEL(响铃)的Unicode值 print(ord('\a')) # 输出: 7
2. 使用string模块的内置常量
Python的string模块提供了预定义的ASCII控制字符常量,导入后直接使用即可:
import string print(ord(string.NUL)) # NUL,输出: 0 print(ord(string.DEL)) # DEL,输出: 127 print(ord(string.CR)) # CR,输出: 13 print(ord(string.LF)) # LF,输出: 10 print(ord(string.BEL)) # BEL,输出: 7
注:string模块还包含string.ascii_controls常量,它是所有ASCII控制字符的字符串集合。
3. 用chr()生成控制字符
如果已知控制字符的ASCII/Unicode数值,也可以用chr()生成对应的字符,再传入ord()验证:
# 生成NUL字符并获取其Unicode值 nul_char = chr(0) print(ord(nul_char)) # 输出: 0 # 生成BEL字符并获取其Unicode值 bel_char = chr(7) print(ord(bel_char)) # 输出: 7
内容的提问来源于stack exchange,提问作者user11717481
相关产品推荐
相关产品推荐

