类型错误:在字典键值的字符串格式化过程中,并非所有参数都被转换

问题描述 投票:0回答:1
a = input("enter the message")
a = list(a)
b = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
     "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
     ",", ".", "?", "!", "@", "#", "$", "%", "^", "&", "*",
     "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
d = {}
for i in a:
    c = 0
    for j in b:
        if i == j:
            
            d[j] = c # Use dictionary assignment instead of update
            
        c = c + 1
print(d)
e = ""
for i in d.keys():
    print(i)
    if i % 2 == 0:
        
        c = int(i / 2)
        f = 0
        for j in b:
            if c == f:
                e = e + j
        
    else:
        c = int((i - 1) / 2)
        f = 0
        for j in b:
            if c == f:
                e = e + j
print(e)

我不知道如何解决它。我是编程新手,没有太多想法。 请帮助我如何修复它。 我知道字典中的键是整数,但它仍然给出错误。 它给

TypeError: not all arguments converted during string formatting

python python-3.x dictionary
1个回答
0
投票

我猜测您正在尝试构建一个简单的加密/解密算法。 我使用字符的 ascii 值作为键,以使其更方便。 在第二个循环中,您尝试迭代字典 d 的键(字符)。然后您尝试直接对这些字符执行算术运算(% 2, / 2)。这不会按预期工作

这是修改后的代码,应该可以正常工作

a = input("Enter the message: ")
a = list(a)
b = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
     "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
     ",", ".", "?", "!", "@", "#", "$", "%", "^", "&", "*",
     "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]

d = {}
for i in a:
    for j, char in enumerate(b):
        if i == char:
            d[i] = j

print("Encrypted Dictionary:", d)

e = ""
for i in d.keys():
    index = d[i]
    if index % 2 == 0:
        c = int(index / 2)
    else:
        c = int((index - 1) / 2)
    e += b[c]

print("Decrypted message:", e)
© www.soinside.com 2019 - 2024. All rights reserved.