2014-02-19 30 views
1

我目前正在尝试制作一个凯撒解码器,所以我正试图找出如何让用户输入值的变化,并使用该输入来移动列表中的每个项目。但每次尝试时,都会给我一个错误。如何增加列表中每个项目/元素的值?

例如:

word在ASCII是:

[119, 111, 114, 100] 

如果移给定的输入是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 

而且,这将是有益的,如果你们不使用任何花哨的功能而是,请使用现有的代码,我是新手

回答

6

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] 
>>> 
+0

+1的解释 –

1

如果你有兴趣在一个班轮:。

shifted_word = "".join([chr(ord(letter)+shift_value) for letter in word]) 
相关问题