Python中的字符串和字典

时间:2013-10-26 23:04:20

标签: python string dictionary encryption

我想创建一个简单的密码。

alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
key =   "XPMGTDHLYONZBWEARKJUFSCIQV"

def main():
  while True:
      plain = raw_input("text to be encoded: ")
      print encode(plain)

def encode(plain):
      length = len(plain)
      plain = plain.upper()
      for c in plain:
          encoded = _______
      return encoded 
  

输入:CAT,输出:MXU

我有这个模板,但最好的方法是什么?如果我必须使用字典,我如何在给定的设置中使用它?

3 个答案:

答案 0 :(得分:3)

一种非常有效的方法是使用.translate()字符串方法:

import string

alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
key = "XPMGTDHLYONZBWEARKJUFSCIQV"

cipher = string.maketrans(alpha, key)

def encode(plaintext):
    return plaintext.translate(cipher)

答案 1 :(得分:2)

用你的两个字符串:

alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
key =   "XPMGTDHLYONZBWEARKJUFSCIQV"

使用zip()

创建字典
mydict = {k:v for k, v in zip(alpha, key)} # Or dict(zip(alpha, key))

然后在encode()函数中,您可以执行以下操作:

def encode(plain):
    return ''.join([mydict.get(i, i) for i in plain])

[mydict.get(i, i) for i in plain]相当于:

newlist = []
for i in plain:
    newlist.append(mydict.get(i, i))

mydict.get(i, i)相当于mydict[i],但如果没有键i,则返回i(第二个参数)(而不是引发KeyError)< / p>

请注意,该列表会返回['M', 'X', 'U']之类的内容,因此''.join()会将其打印为'MXU'

答案 2 :(得分:1)

alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
key = "XPMGTDHLYONZBWEARKJUFSCIQV"

inp = 'CAT'

_d = {e[0]: e[1] for e in zip(alpha, key)}

print _d


print ''.join([_d[ele] for ele in inp if ele in _d])