繁体   English   中英

如何使打印词典的一部分打印出数学值?

[英]How can I make printing a portion of a dictionary print the mathematical value?

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

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

您的密钥是一个字符串(一个字符,但仍然是一个字符串)。 因此在实践中"1"*3 = "111" 要执行您期望的操作,请使用key = int(input(...))

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM