python如何拆分字符串并重新连接它

python如何拆分字符串并重新连接它,python,string,replace,Python,String,Replace,我正在用python进行加密作业,我需要: -拆线 -替换字母 -重新连接它,使其成为一个单词 这是完整的代码,但我被困在def encode(普通)下的for循环中 实现此替换的最简单方法是使用字典和列表理解: alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" key = "XPMGTDHLYONZBWEARKJUFSCIQV" converter = {a:b for a, b in zip(alpha, key)} def encode(s): return

我正在用python进行加密作业,我需要: -拆线 -替换字母 -重新连接它,使其成为一个单词

这是完整的代码,但我被困在
def encode(普通)
下的for循环中


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

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

如果您试图实现自己的解决方案,请按照@Ajax1234所说的去做

但更容易使用


示例输入和预期输出会很好。您需要在函数定义下缩进代码Cret decoder(加密解码器)菜单0)退出1)编码2)解码您想做什么?1要编码的文本:hello L T Z Z E hello这是当我打印出Z时发生的事情,我希望它以一个单词的形式显示出来,但我的教授告诉我们只使用标准代码,所以我们不能使用translate()方法。我们也不能更改main()函数,所以我们基本上必须使用字符串操作来转换秘密消息。在def encode(plain)下,我已经将字符串“plain”切片,并将字符与字符串“alpha”和“key”进行比较,但我不知道如何将它们重新组合成一个单词。在您的代码中,
reverse
converter
的结果相同。我会使用
converter=dict(zip(alpha,key))
reverse=dict(zip(key,alpha))
(或者
reverse={b:a代表a,b在converter.items()}
)。@MatthiasFripp感谢您指出这一点。请看我最近的编辑。
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()
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)