python如何分割字符串并重新加入
我在做python中的加密分配,我需要: - 分割字符串 - 替换字母 - 重新加入它,以便它是一个单词。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()
实现这个替代的最简单的方法是使用字典和列表理解:
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()
在你的代码中,'reverse'和'converter'结束。我将使用'converter = dict(zip(alpha,key))'和'reverse = dict(zip(key,alpha))'(或'reverse = {b:a for a,b in converter.items()} ')。 –
@MatthiasFripp谢谢你指出。请参阅我最近的编辑。 – Ajax1234
如果你想实现自己的解决方案也为@ 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)
我的教授告诉我们只使用标准代码,所以我们不能使用translate()方法。我们也不能改变main()函数,所以我们基本上必须使用字符串操作来转换秘密消息。在def encode下(普通),我已经将字符串“plain”切片并将字符与字符串“alpha”和“key”进行比较,但我不知道如何再次将它们组合成一个单词 – Matteo
样品的输入和输出预计将是很好的。 –
你需要在你的函数定义下缩进代码 – 0TTT0
解密器菜单的秘密 0)退出 1)编码 2)解码 你想做什么? 文本进行编码:你好 大号 牛逼 ž ž Ë HELLO – Matteo