【问题标题】:Printing an inputted list of ASCII codes as a list of characters将输入的 ASCII 代码列表打印为字符列表
【发布时间】:2023-03-25 09:01:01
【问题描述】:

我是一个完整的新手程序员,我无法将用户输入的 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 = input("请输入您的ASCII码:")
  • ascii_code = int(input("请输入您的ASCII码:"))
  • ascii_code = eval(input("请输入您的ASCII码:"))

我得到 TypeError: an integer is required (got type str) 或 TypeError: 'int' object is not iterable。

任何帮助将不胜感激!

【问题讨论】:

  • input 通话期间您想输入什么?
  • ASCII 码列表,例如:109、121、32、110、97、..等
  • 好吧,您从输入中得到一个 str,所以只需处理 str... 阅读拆分和剥离也许?然后 int 你从中得到了什么?

标签: python python-3.x input ascii typeerror


【解决方案1】:

你从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']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-21
    • 2020-07-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-23
    • 2019-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多