use*_*078 1 python list decoder python-2.x
我目前正在尝试制作凯撒解码器,所以我试图找出如何获取用户输入的移位值,并使用该输入来移动列表中的每个项目.但每次我尝试,它只是一直给我一个错误.
例如:
word
在ASCII中将是:
[119, 111, 114, 100]
Run Code Online (Sandbox Code Playgroud)
如果转移的给定输入是2
,我希望列表是:
[121, 113, 116, 102]
Run Code Online (Sandbox Code Playgroud)
请帮忙.这是我的第一次编程和这个凯撒解码器让我发疯:(
这就是我到目前为止所拥有的
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
Run Code Online (Sandbox Code Playgroud)
此外,如果你们不使用任何花哨的功能,将会很有帮助.相反,请使用现有代码.我是新手.
raw_input
返回一个字符串对象并ord
返回一个整数.此外,正如错误消息所述,您无法将字符串和整数与+
以下内容一起添加:
>>> 'a' + 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>>
Run Code Online (Sandbox Code Playgroud)
但是,这正是您在此尝试做的事情:
toConv = [x+key for x in toConv]
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,x
将是一个整数(因为toConv
是一个整数列表)并且key
将是一个字符串(因为你曾经raw_input
得到它的值).
您只需将输入转换为整数即可解决问题:
key = int(raw_input("What is the key value or the shift? "))
Run Code Online (Sandbox Code Playgroud)
之后,您的列表理解将按预期工作.
以下是演示:
>>> 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]
>>>
Run Code Online (Sandbox Code Playgroud)