pythonascii码转换函数
推荐
在线提问>>
Python提供了内置的函数来进行ASCII码和字符之间的转换。下面是一些常用的函数:
## chr()函数
chr()函数用于将ASCII码转换为对应的字符。它接受一个整数作为参数,返回对应的字符。
`python
num = 65
char = chr(num)
print(char) # 输出'A'
## ord()函数
ord()函数用于将字符转换为对应的ASCII码。它接受一个字符作为参数,返回对应的整数值。
`python
char = 'A'
num = ord(char)
print(num) # 输出65
## 示例:将字符串中的字符转换为对应的ASCII码
`python
string = "Hello, World!"
for char in string:
num = ord(char)
print(f"The ASCII code of {char} is {num}")
输出结果:
The ASCII code of H is 72
The ASCII code of e is 101
The ASCII code of l is 108
The ASCII code of l is 108
The ASCII code of o is 111
The ASCII code of , is 44
The ASCII code of is 32
The ASCII code of W is 87
The ASCII code of o is 111
The ASCII code of r is 114
The ASCII code of l is 108
The ASCII code of d is 100
The ASCII code of ! is 33
## 示例:将ASCII码转换为对应的字符并拼接成字符串
`python
nums = [72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33]
string = ""
for num in nums:
char = chr(num)
string += char
print(string) # 输出"Hello, World!"
希望以上内容能够帮助你理解如何在Python中进行ASCII码和字符之间的转换。如果你有任何其他问题,请随时提问!