gpt4 book ai didi

python - 在使用 ord([a word]) 时,我遇到一个问题,说它是一个数字

转载 作者:行者123 更新时间:2023-11-30 23:10:57 25 4
gpt4 key购买 nike

我正在尝试将用户输入的单词转换为数字。我输入一个单词,但出现以下错误:

step1 = ord(letter)

TypeError: ord() expected string of length 1, but int found

这是我的代码(我在此之前删除了一些不必要的内容):

phrase = str(input("Enter sentence"))
list = []
for letter in phrase:
list.append(letter)
maxlist = len(list)
convert = True
while convert == True :
for letter in list :
counter = 0
while counter < maxlist :
step1 = ord(letter)
list[0 + counter] = step1
counter = counter + 1

最佳答案

您将用整数替换列表中的值:

step1 = ord(letter)
list[0 + counter] = step1

您的下一个 while 循环迭代将使用这些整数而不是字母。

其他说明:

  • 不要使用 list 作为变量名称,您会屏蔽 list 内置变量。
  • 将字符串转换为字符列表就像使用您屏蔽的内置函数一样简单:

    characters = list(phrase)
  • 不要使用== Truewhileif 已经在测试真值,您正在冗余地检查这种可能性,将 True 转换为 True .
  • 将句子转换为整数非常简单:

    phrase = str(input("Enter sentence"))
    converted = [ord(character) for character in phrase]

关于python - 在使用 ord([a word]) 时,我遇到一个问题,说它是一个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30415717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com