Ord函数用法举例子
时间: 2024-09-20 19:08:22 浏览: 40
php字符串截取函数用法分析
`ord()`函数在Python中用于获取一个字符的Unicode编码值。下面是一些例子:
1. 获取单个字符的Unicode码点[^1]:
```python
char = 'A'
unicode_value = ord(char)
print(f"The Unicode value of '{char}' is {unicode_value}.") # 输出: The Unicode value of 'A' is 65.
```
2. 对于非ASCII字符,如汉字:
```python
char = '你好'
unicode_value = ord(char[0])
print(f"The Unicode value of the first character '{char[0]}' is {unicode_value} (for the full string it's {ord(char)})")
```
注意,`ord()`只对单个字符有效,所以`char[0]`用来提取第一个字符。
3. 如果输入非字符类型,会抛出异常:
```python
try:
invalid_input = 123
unicode_value = ord(invalid_input) # 这会引发 TypeError
except TypeError as e:
print(e) # 输出: ord() expected a character, but string of length 1 found
```
阅读全文