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

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

4

4 回答 4

6

您的原始代码给您错误的原因是line.replace(data, code, [data]). 该str.replace方法可以采用3 个参数。第一个是您要替换的字符串,第二个是替换字符串,第三个可选参数是您要替换的字符串的实例数 - 一个整数。您正在传递一个列表作为第三个参数。

但是,您的代码也存在其他问题。

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)
于 2013-03-02T00:27:31.460 回答
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)

% python ./test.py

larry
12334
于 2013-03-02T00:39:41.867 回答
1

您可以使用翻译

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

(假设 Python 3)

于 2013-03-02T00:51:43.680 回答
0

前面的评论应该可以很好地解释你的错误信息,所以我只会给你另一种方法来翻译 from datato code。我们可以利用 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


仅作记录,如果您对编码数据感兴趣,您应该检查 hashing
散列法是一种广泛使用的生成秘密数据格式的方法。

一个简单的 Python 哈希示例(使用所谓的 sha256 哈希方法):

>>> import hashlib
>>> data = raw_input('statement: ')
statement: larry
>>> secret_data = hashlib.sha256(data)
>>>print secret_data.hexdigest()
0d098b1c0162939e05719f059f0f844ed989472e9e6a53283a00fe92127ac27f
于 2013-03-02T01:07:42.060 回答