`ord()` 是Python的一个内置函数,用于返回单个字符的Unicode码点。下面是如何使用 `ord()` 函数的一些基本示例:
1. 获取字符的Unicode码点:
print(ord('A')) 输出:65
print(ord('a')) 输出:97
print(ord('中')) 输出:20013
2. 验证用户输入是否为单个字符:
def is_single_char(char):
return isinstance(char, str) and len(char) == 1
user_input = input("请输入一个字符:")
if is_single_char(user_input):
print(f"输入字符的Unicode码点是:{ord(user_input)}")
else:
print("输入错误,请输入单个字符。")
3. 大小写字母转换:
def to_lower(char):
if 'A' <= char <= 'Z':
return chr(ord(char) + 32)
return char
print(to_lower('A')) 输出:'a'
4. 判断字符类型:
def check_char_type(char):
if 'a' <= char <= 'z':
return "小写字母"
elif 'A' <= char <= 'Z':
return "大写字母"
elif '0' <= char <= '9':
return "数字"
else:
return "其他字符"
print(check_char_type('a')) 输出:小写字母