基本上我有一个非常简单地加密消息的功能。
def encrypt(message):
alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
key = ["4","x","z","@","%","b","j","q","(","ƒ","¥","µ","˚","nå","ø","π","å","œ","¢","∞","∫","µ","≈","`","¬","…"]
new_message = ""
for x in range(0,len(message)):
new_message = message.replace(message[x],key.index[alphabet.index(message[x])])
return new_message
print(encrypt(input("What would you like to encrypt").lower()))
这应该取信并将其替换为list键中具有相同索引的字符,但是我收到错误:
TypeError: 'builtin_function_or_method' object is not subscriptable
答案 0 :(得分:2)
key.index()
获取一个值并返回其索引,并使用()
而不是[]
,因此您需要修复此行:
new_message = message.replace(message[x],key.index[alphabet.index(message[x])])
为:
new_message = message.replace(message[x],key[alphabet.index(message[x])])
这将使用字母索引并使用它来访问key
列表并获取该索引处的值以将其替换为原始字母。
修改强>
更好的方法是使用dictionary
并构造一个新的字符串,以避免在replace()
string
dic = {'a': '4', 'b': 'x', 'c': 'z' ...}
new_message = ''
for x in message:
new_message += dic[x]
return new_message
答案 1 :(得分:2)
我建议使用中间console.log
来创建DATA 2
列表项与 function testIterate() {
return q.all(_.map(params.attachments, function (a) {
var deferred = q.defer();
var filePath = path.join(tempDir, a.fileName);
//console.log('ATTACHMENT BUFFER ::: ', a.buffer);
fs.writeFile(filePath, a.buffer, function (err) {
if (err) {
// error
}
// Iterate letters to create unique keys for each attachment
var letter = String.fromCharCode('A'.charCodeAt() + idx);
var fileKey = "attachment" + letter;
deferred.resolve(
formData[fileKey] = {
value: fs.createReadStream(filePath),
options: {
filename: a.fileName,
//path: filePath,
contentType: a.contentType
}
}
);
console.log('THIS IS THE FORM DATA 1 :: ', formData);
// Increment to assign unique letter to next attachment key
idx++;
});
return deferred.promise;
})).then(function (results) {
console.log('THIS IS THE FORM DATA 2 :: ', results);
});
}
列表项的映射:
dict
然后使用上面的字典和alphabet
来转换你的字符串。例如:
key
答案 2 :(得分:2)
最后是str.translate
的用例!
def encrypt(message):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
key = '4xz@%bjq(ƒ¥µ˚nåøπ圢∞∫µ≈`¬'
table = str.maketrans(alphabet, key)
return message.translate(table)
print(encrypt('asdsaewqeq')) # 4œ@œ4%µπ%π
请注意,key
中的某个条目由两个字符组成。如果这是故意的,并且您想要用2替换单个字符,则可以手动创建转换表。
table = dict(zip(map(ord, alphabet), key))