当运行此代码并输入abcdefg ...作为文本而输入1作为键时,我希望它输出12345 ...,因为这是一个基本的加密程序。然而它输出 1 11 111 1111等 有什么问题,如何解决这个问题。
choice = input("Would you like to encrypt or decrypt? e/n")
text = input("Enter text: ")
key = input("Enter key: ")
################################
def encrypt(clear, key):
Meow = {"a" : 1*key, "b" : 2*key, "c" : 3*key,"d" : 4*key,"e" : 5*key,"f" : 6*key,"g" : 7*key,"h" : 8*key,"i" : 9*key,"j" : 10*key,"k" : 11*key,"l" : 12*key,"m" : 13*key,"n" : 14*key,"o" : 15*key,"p" : 16*key,"q" : 17*key,"r" : 18*key,"s" : 19*key,"t" : 20*key,"u" : 21*key,"v" : 22*key,"w" : 23*key,"x" : 24*key,"y" : 25*key,"z" : 26*key}
x = 0
while(x<len(clear)):
print(Meow[clear[x]])
x = x + 1
################################
if choice == "e":
encrypt(text, key)
elif choice == "n":
print("finish")
else:
print("Please enter either e or n")
另外,有更简单的方法来做字典吗?
答案 0 :(得分:2)
您的密钥是一个字符串(一个字符,但仍然是一个字符串)。所以在实践中"1"*3 = "111"
。要做到您期望的,请使用key = int(input(...))
答案 1 :(得分:2)
input()
retun值是一个字符串。
Python为字符串(和其他序列)实现乘法运算符。当其他方参数是自然数时,它可以工作。 n
的乘法实现为复制整个序列n
次,例如:
assert "abc" * 3 == "abcabcabc"
assert "12" * 4 = "12121212"
assert [1, 2, 3] * 2 = [1, 2, 3, 1, 2, 3] # it works for lists too!
要获取数字值,您必须将字符串转换为整数。
s = "12" # s = input()
i = int(s)
assert i == 12