Python 函数 —— ord(), chr()

本文介绍了如何使用Python内置函数chr()和ord()进行Unicode字符与整数之间的相互转换。chr()函数接受一个整数作为参数,并返回对应的Unicode字符;ord()函数则相反,它接受一个Unicode字符并返回其对应的整数值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

chr(i)

Return the string representing a character whose Unicode code point is the integer i. For example, chr(97) returns the string ‘a’, while chr(8364) returns the string ‘€’. This is the inverse of ord().

The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in base 16). ValueError will be raised if i is outside that range.

In [4]: chr(14)
Out[4]: '\x0e'

In [5]: chr(44)
Out[5]: ','

In [6]: chr(60)
Out[6]: '<'

ord(c)

Given a string representing one Unicode character, return an integer representing the Unicode code point of that character. For example, ord(‘a’) returns the integer 97 and ord(‘€’) (Euro sign) returns 8364. This is the inverse of chr().

In [7]: ord('a')
Out[7]: 97

In [8]: chr(97)
Out[8]: 'a'
### Python `ord()` 和 `chr()` 函数使用方法 #### 1. 函数概述 `ord()` 和 `chr()` 是用于字符和整数(通常是ASCII或Unicode码位)之间相互转换的内置函数。这两个函数在处理字符编码时非常有用,尤其是在涉及文本处理的应用程序中[^2]。 #### 2. `ord()` 函数详解 `ord()` 接受单个字符作为参数并返回对应的整数值,该值代表给定字符的Unicode码点,在ASCII范围内即为相应的ASCII码。这意味着对于任何有效的单一字符输入,此函数都会提供一个唯一的数字表示形式[^3]。 ```python print(ord('A')) # 输出: 65 print(ord('a')) # 输出: 97 ``` #### 3. `chr()` 函数详解 相反地,`chr()` 将接受一个整数参数,并返回与之相对应的字符。这个过程实际上是`ord()`操作的逆向版本;它能够把由`ord()`产生的整数重新变回原始字符[^4]。 ```python print(chr(65)) # 输出: A print(chr(97)) # 输出: a ``` #### 4. 实际应用场景 为了更直观地展示这两个函数的工作原理及其潜在用途,下面给出了一些具体的例子: - **基本转换** ```python for i in range(65, 68): # ASCII values for 'A' to 'C' char = chr(i) ascii_val = ord(char) print(f"Character {char} has ASCII value {ascii_val}") ``` - **字符串遍历** 当需要逐字分析字符串或将整个字符串映射到其各自的ASCII/Unicode码时,可以组合使用这些功能来实现目标[^1]。 ```python text = "Hello" encoded_text = [str(ord(c)) for c in text] decoded_text = ''.join([chr(int(code)) for code in encoded_text]) print(encoded_text) # ['72', '101', '108', '108', '111'] print(decoded_text) # Hello ``` 通过上述实例可以看出,掌握好`ord()`和`chr()`不仅有助于加深对Python内部工作机制的理解,而且可以在实际项目开发过程中发挥重要作用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值