2013-03-02 73 views
4

我想写一个程序来转换一个消息无损秘密代码。我试图创建一个基本的代码来处理。这是问题。可以将一个列表转换为一个整数

data = input('statement') 
for line in data: 
    code = ('l' == '1', 
      'a' == '2' 
      'r' == '3', 
      'y' == '4') 
    line = line.replace(data, code, [data]) 
print(line)  

这一点上面编程'是如此,当我输入我的名字:

larry 

输出应该是

12334 

,但我仍然收到此消息

TypeError: 'list' object cannot be interpreted as an integer 

所以我认为这意味着我的代码变量必须是一个整数用于替换() 有没有办法将该字符串转换为整数或有另一种方法来解决这个问题?

+0

边注:由于'data'实际上只是一个线串,这将是误导在数据中使用':char',而不是'in line in data:'。 – abarnert 2013-03-02 00:39:38

回答

6

你原来的代码给你错误的原因是因为line.replace(data, code, [data])str.replace方法可以采取3 arguments。第一个是要替换的字符串,第二个是替换字符串,第三个可选参数是要替换的字符串的多少个实例 - 一个整数。你是通过一个列表作为第三个参数。

但是,您的代码还有其他问题。

code当前为(False, False, False, False)。你需要的是一个字典。您可能还想将其分配到循环之外,因此您不必在每次迭代中对其进行评估。

code = {'l': '1', 'a': '2', 'r': '3', 'y': '4'} 

然后,你的循环改成这样:

data = ''.join(code[i] for i in data) 

print(data)为您提供所需的输出。

但是,请注意,如果输入中的字母不在字典中,则会出现错误。如果密钥不在字典中,您可以使用dict.get方法提供默认值。

data = ''.join(code.get(i, ' ') for i in data) 

其中code.get的第二个参数指定了默认值。

所以,你的代码应该是这样的:

code = {'l': '1', 'a': '2', 'r': '3', 'y': '4'} 

data = input() 
data = ''.join(code.get(i, ' ') for i in data) 

print(data) 
1

只是为了总结:

%的猫./test.py

#!/usr/bin/env python 
data = raw_input() 
code = {'l': '1', 'a': '2', 
     'r': '3', 'y': '4'} 

out = ''.join(code[i] for i in data) 
print (out) 

%蟒蛇./test。PY

larry 
12334 
1

您可以使用translate

>>> print("Larry".lower().translate(str.maketrans('lary', '1234'))) 
12334 

(假设的Python 3)

0

先前的评论应该给你对你的错误消息,一个很好的解释, 所以我只会给你另一种方式使翻译从datacode。 我们可以利用Python的translate方法。

# We will use the "maketrans" function, which is not included in Python's standard Namespace, so we need to import it. 
from string import maketrans 

data = raw_input('statement') 
    # I recommend using raw_input when dealing with strings, this way 
    # we won't need to write the string in quotes. 

# Now, we create a translation table 
# (it defines the mapping between letters and digits similarly to the dict) 
trans_table = maketrans('lary', '1234') 

# And we translate the guy based on the trans_table 
secret_data = data.translate(trans_table) 

# secret_data is now a string, but according to the post title you want integer. So we convert the string into an integer. 
secret_data = int(secret_data) 

print secret_data 


只是为了记录在案,如果你有兴趣的编码数据,你应该检查 散列
散列是一种广泛使用的生成秘密数据格式的方法。

在Python散列(使用所谓的SHA256散列法)的一个简单的例子:

>>> import hashlib 
>>> data = raw_input('statement: ') 
statement: larry 
>>> secret_data = hashlib.sha256(data) 
>>>print secret_data.hexdigest() 
0d098b1c0162939e05719f059f0f844ed989472e9e6a53283a00fe92127ac27f 
+0

我刚刚注意到你正在使用Python-3.x ..我写的代码在Python-2.7中工作,我猜基本上它应该和3.x一样,但是请注意可能存在一些细微的差异。 – 2013-03-02 01:18:27

相关问题