我想创建一个非常小的程序,将字母字符转换为ascii_values,反之亦然,但是当提到正在处理的当前字符的ascii值时,会引发错误。
TypeError:ord()期望的字符串长度为1,但是找到了int
这是代码(只是获取错误的部分)
def character_to_ascii_value(char):
print("The ASCII value of", char, "is:", ord(char))
character = "A"
for i in range(25):
character_to_ascii_value(character)
character = ord(character) + 1
PS:已经搜索过但无法找到...(没有得到其他答案)
PS no2:我找到了一个解决方案,但它不是pythonic ...转换这个和那个然后再添加它等等......我认为必须有更简单的东西
character = "A"
char_ascii = ord(character)
for i in range(25):
character_to_ascii_value(character)
char_ascii += 1
character = chr(char_ascii)
答案 0 :(得分:3)
import string
for char in string.ascii_uppercase:
print("The ASCII value of", char, "is:", ord(char))
使用chr()
将数字转换为字符串:
def character_to_ascii_value(char):
print("The ASCII value of", char, "is:", ord(char))
character = "A"
for i in range(25):
character_to_ascii_value(character)
character = chr(ord(character) + 1)
输出:
The ASCII value of A is: 65
The ASCII value of B is: 66
The ASCII value of C is: 67
The ASCII value of D is: 68
The ASCII value of E is: 69
The ASCII value of F is: 70
答案 1 :(得分:0)
您必须从ASCII号码转换回char
。用
character = chr(ord(character) + 1)