python如何拆分字符串并重新加入它

时间:2017-10-21 00:46:39

标签: python string replace

我在python中进行加密分配,我需要: - 拆分一个字符串 - 替换字母 - 重新加入它,这是一个字。

这是完整的代码,但我被def encode(plain)下的for循环停留。

""" crypto.py
Implements a simple substitution cypher
"""

alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
key =   "XPMGTDHLYONZBWEARKJUFSCIQV"

def menu():

    print("Secret decoder menu")
    print("0) Quit")
    print("1) Encode")
    print("2) Decode")
    print("What do you want to do?")
    response = input()
    return response

def encode(plain):

for i in range(len(plain)):

    plain = plain.upper()
    x = plain[i:i+1]
    y = alpha.index(x)
    z = key[y:y+1]
    plain[x] = z

return plain

def main():

keepGoing = True
  while keepGoing:

    response = menu()

    if response == "1":

        plain = input("text to be encoded: ")
        print(encode(plain))

    elif response == "2":
       coded = input("code to be decyphered: ")
       print (decode(coded))

    elif response == "0":
       print ("Thanks for doing secret spy stuff with me.")
       keepGoing = False

    else:
       print ("I don't know what you want to do...")

return main

main()
menu()

2 个答案:

答案 0 :(得分:1)

实现此替换的最简单方法是使用字典和列表解析:

alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
key = "XPMGTDHLYONZBWEARKJUFSCIQV"
converter = {a:b for a, b in zip(alpha, key)}
def encode(s):
   return ''.join(converter[i] for i in s)

def decode(s):
   reverse = {b:a for a, b in converter.items()}
   return ''.join(reverse[i] for i in s)

def main():
   response = input("Enter 1 to decode, 2 to encode: ")
   if response == "1":
      the_string = input("Enter the scrambled string: ")
      print("The result is ", decode(the_string))
   elif response == "2":
       the_string = input("Enter the plain string: ")
       print("The result is ", encode(the_string))
main()

答案 1 :(得分:0)

如果您正在尝试实施自己的解决方案,请按@ Ajax1234说。

但使用string translate

更容易
alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
key =   "XPMGTDHLYONZBWEARKJUFSCIQV"
crypto = maketrans(alpha, key)

....
the_string = input("Enter the scrambled string: ")
the_string = the_string.upper()
encrypted = the_string.translate(crypto)