在python中,`ord()`与`chr()`是一对互逆函数,配合使用可以实现字符与unicode码位之间的双向转换。具体做法是:调用`ord(char)`获取单个字符串对应的整数码位,调用`chr(code)`将整数还原为对应的字符。这种配合常用于字符编码检查、简单的加密偏移或生成连续字符序列。

如何验证一个字符是否为基本拉丁字母
要判断一个字符是否属于基本拉丁字母(A-Z, a-z),可以分别获取其大写和小写形式的码位范围进行比对。通过`ord()`获取当前字符的码位,并与'A'、'Z'、'a'、'z'的码位比较,即可确定其类别。这种方法比正则表达式更底层,适合需要精确控制编码逻辑的场景。

def check_latin_char(c):
if len(c) != 1:
return "Input must be a single character"
code = ord(c)
upper_start = ord('A')
upper_end = ord('Z')
lower_start = ord('a')
lower_end = ord('z')
if upper_start <= code <= upper_end:
return "Uppercase Latin"
elif lower_start <= code <= lower_end:
return "Lowercase Latin"
else:
return "Not a Basic Latin Letter"
# Test cases
print(check_latin_char('A')) # Uppercase Latin
print(check_latin_char('m')) # Lowercase Latin
print(check_latin_char('5')) # Not a Basic Latin Letter
print(check_latin_char('中')) # Not a Basic Latin Letter预期输出:
Uppercase Latin
Lowercase Latin
Not a Basic Latin Letter
Not a Basic Latin Letter
立即学习“Python免费学习笔记(深入)”;
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。
如何实现简单的凯撒密码偏移
实现凯撒密码的核心在于利用`ord()`和`chr()`对字符码位进行算术偏移。对于英文字母,先将其转换为0-25的索引,加上偏移量后取模26,再转回字符。非字母字符通常保持不变。这个过程展示了两个函数在处理文本变换时的典型协作模式。

def caesar_cipher(text, shift):
result = []
for char in text:
if char.isupper():
# 'A' is 65, 'Z' is 90
shifted = (ord(char) - ord('A') + shift) % 26 + ord('A')
result.append(chr(shifted))
elif char.islower():
# 'a' is 97, 'z' is 122
shifted = (ord(char) - ord('a') + shift) % 26 + ord('a')
result.append(chr(shifted))
else:
result.append(char)
return ''.join(result)
# Example: Shift by 3
original = "Hello World!"
encrypted = caesar_cipher(original, 3)
decrypted = caesar_cipher(encrypted, -3)
print(f"Original: {original}")
print(f"Encrypted: {encrypted}")
print(f"Decrypted: {decrypted}")预期输出:
Original: Hello World!
Encrypted: Khoor Zruog!
Decrypted: Hello World!
当输入超出Unicode范围时会发生什么
如果向`chr()`传入一个不在有效Unicode范围内的整数(例如负数或大于0x10FFFF的数),Python会抛出`ValueError`异常。而`ord()`始终接受单个字符并返回合法的整数,不会越界。因此在使用两者配合时,需确保传递给`chr()`的值在合法区间内,否则程序会中断。

















