如何使打印成为字典的一部分打印数学值?

时间:2015-12-07 21:56:33

标签: python python-3.x

当运行此代码并输入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")

另外,有更简单的方法来做字典吗?

2 个答案:

答案 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