2013-03-02 107 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

相關問題