python - 找不到根据键翻译字符串的简单方法

标签 python list python-3.x indexing

基本上我有一个函数可以非常简单地加密消息。

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()))

这应该取字母并将其替换为列表键中具有相同索引的字符,但是我收到错误:

TypeError: 'builtin_function_or_method' object is not subscriptable

最佳答案

最后是 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 中的一个条目由两个字符组成。如果这是有意的并且您想用两个字符替换单个字符,那么您可以手动创建翻译表。

table = dict(zip(map(ord, alphabet), key))

关于python - 找不到根据键翻译字符串的简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44766703/

相关文章:

python - 使用正则表达式或常规 Python 进行字符串替换?

python - {m,n} 吗?正则表达式实际上最大限度地减少了重复,还是最大限度地减少了匹配的字符数?

python - 检测训练集的频率

python - 在 python 中绘制自定义图表

python - 从现有文件中提取多个新的制表符分隔文件

python - apply() 函数和使用类对象的函数调用有什么区别?

python - 将可迭代的所有元素添加到列表

c++ - 如何将这些自定义对象列表的时间复杂度从 O(n) 降低到 O(1)?

python - PyMongo upsert 抛出 "upsert must be an instance of bool"错误

list - 将字符添加到频率列表