簡體   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