我目前正在尝试制作一个 Caesar 解码器,因此我正在尝试找出如何获取用户输入的移位值,并使用该输入来移位列表中的每个项目。但每次我尝试时,它总是给我一个错误。
例如:
ASCII 中的word 将是:
[119, 111, 114, 100]
如果给定的 shift 输入是 2,我希望列表是:
[121, 113, 116, 102]
请帮忙。这是我第一次编程,这个凯撒解码器快把我逼疯了:(
这是我目前的情况
import string
def main():
inString = raw_input("Please enter the word to be "
"translated: ")
key = raw_input("What is the key value or the shift? ")
toConv = [ord(i) for i in inString] # now want to shift it by key value
#toConv = [x+key for x in toConv] # this is not working, error gives 'cannot add int and str
print "This is toConv", toConv
此外,如果你们不使用任何花哨的功能,那将会很有帮助。相反,请使用现有代码。我是新手。
请您参考如下方法:
raw_input返回一个字符串对象和 ord返回一个整数。此外,如错误消息所述,您不能将字符串和整数与 + 相加:
>>> 'a' + 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>>
但是,这正是您在这里尝试做的:
toConv = [x+key for x in toConv]
在上面的代码中,x 将是一个整数(因为 toConv 是一个整数列表)而 key 将是一个字符串(因为你使用 raw_input 来获取它的值)。
您可以通过简单地将输入转换为整数来解决问题:
key = int(raw_input("What is the key value or the shift? "))
之后,您的列表理解将正常工作。
下面是一个演示:
>>> def main():
... inString = raw_input("Please enter the word to be "
... "translated: ")
... # Make the input an integer
... key = int(raw_input("What is the key value or the shift? "))
... toConv = [ord(i) for i in inString]
... toConv = [x+key for x in toConv]
... print "This is toConv", toConv
...
>>> main()
Please enter the word to be translated: word
What is the key value or the shift? 2
This is toConv [121, 113, 116, 102]
>>>
