简体   繁体   English

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

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

When running this code and entering abcdefg... as the text and 1 as the key, I want it to output 12345..., as this is a basic encryption program. 运行此代码并输入abcdefg ...作为文本和1作为密钥时,我希望它输出12345 ...,因为这是一个基本的加密程序。 However it outputs 1 11 111 1111 etc. What is wrong and how can I fix this. 但是,它输出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")

Also, is there an easier way to do the dictionary? 另外,有没有更简单的方法来做字典?

Your key is a string (one character, but still a string). 您的密钥是一个字符串(一个字符,但仍然是一个字符串)。 So in practice "1"*3 = "111" . 因此在实践中"1"*3 = "111" To do what you expect, use key = int(input(...)) 要执行您期望的操作,请使用key = int(input(...))

input() retun value is a string. input() retun值是一个字符串。

Python implements multiply operator for strings (and other sequences). Python为字符串(和其他序列)实现了乘法运算符。 It works when other side argument is a natural number. 当另一边参数为自然数时,此方法有效。 Multiplication by n is implemented as replicating whole sequence n times, for example: 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!

To get number values you have to convert your string to integer. 要获取数字值,您必须将字符串转换为整数。

s = "12"  # s = input()
i = int(s)
assert i == 12

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

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