首页 文章

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

提问于
浏览
0

我是一个完整的新手程序员,并且无法将用户输入的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列表时(在第一行代码中)但在我尝试运行输入时工作,例如:

  • ascii_code =输入("Please input your ASCII code:")

  • ascii_code = int(输入("Please input your ASCII code:"))

  • ascii_code = eval(输入("Please input your ASCII code:"))

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

任何帮助将非常感激!

1 回答

  • 0

    input() 得到的结果是元组(python 2,所以使用 raw_input() 来获得正确的行为)或字符串(python 3) . 我'll assume you'使用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']
    

相关问题