将输入的 ASCII 码列表打印为字符列表

Printing an inputted list of ASCII codes as a list of characters

我是一个完全的新手程序员,我无法让用户输入的 ASCII 代码列表打印为字符列表:

ascii_code = [109, 121, 32, 110, 97, 109, 101, 32, 105, 115,
             32, 106, 97, 109, 101, 115]

#ascii_code = input("Please input your ASCII code:")

character_list = list()
for x in ascii_code:
    character_list.append(chr(x))

print (character_list)

['m', 'y', ' ', 'n', 'a', 'm', 'e', ' ', 'i', 's', ' ', 'j', 'a', 'm', 'e', 's']

如您所见,当 ASCII 列表是预定义的(在代码的第一行中)时,该程序可以运行,但是当我尝试 运行 输入时,例如:

我得到类型错误:需要一个整数(得到类型 str)或类型错误:'int' 对象不可迭代。

如有任何帮助,我们将不胜感激!

你从 input() 得到的结果是一个元组(python 2,所以使用 raw_input() 来获得正确的行为)或一个字符串(python 3 ).我假设您正在使用 Python 3 或将切换到使用 raw_input 因为 Python 2 中的 input 只是不好的做法。

您从用户那里得到的结果是一个逗号分隔的字符串。您需要将该字符串分成几部分,您可以使用 .split(','):

>>> s = raw_input('Enter ASCII codes:')
Enter ASCII codes: 1, 2, 3, 4, 5
>>> s.split(',')
[' 1', ' 2', ' 3', ' 4', ' 5']

但是您会注意到列表中的数字是 1) 字符串,而不是整数,并且 2) 周围有空格。我们可以通过遍历数字并使用 .strip() 删除空格和 int() 将剥离的字符串转换为我们可以传递给 chr():

的数字来解决此问题
character_list = []
for p in s.split(','):
    character_list.append(chr(int(s.strip())))

...但更 Pythonic 通过列表理解来做到这一点:

character_list = [ chr(int(p.strip())) for p in s.split(',') ]

所以你的最终代码将是:

>>> s = raw_input('Enter ASCII codes: ')
Enter ASCII codes: 65, 66, 67
>>> character_list = [ chr(int(p.strip())) for p in s.split(',') ]
>>> print(character_list)
['A', 'B', 'C']