Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 涉及加法的类型错误 一次性Pad多字母替换密码_Python - Fatal编程技术网

Python 涉及加法的类型错误 一次性Pad多字母替换密码

Python 涉及加法的类型错误 一次性Pad多字母替换密码,python,Python,程序在第70行停止: num += LETTERS.find(key[keyIndex]) # Add if encrypting 我怎样才能解决这个问题 注意:我知道还有许多其他问题困扰着我的代码 将if-else条件更改为: if mode == 'encrypt': num += LETTERS.find(key[keyIndex]) # Add if encrypting elif mode == 'dec

程序在第70行停止:

num += LETTERS.find(key[keyIndex]) # Add if encrypting
我怎样才能解决这个问题


注意:我知道还有许多其他问题困扰着我的代码

将if-else条件更改为:

            if mode == 'encrypt':
                num += LETTERS.find(key[keyIndex]) # Add if encrypting
            elif mode == 'decrypt':
                num -= LETTERS.find(key[keyIndex]) # Subract if decrypting

这是必需的,因为num的类型是int,并且在程序中查找字母返回str。

您的问题是键[keyIndex]不是字符串。string.find方法只接受字符串

这个程序与Python2.7一样工作正常,但在Python3.2中,这就是问题的根源

解决方案A 在str中换行键[keyIndex]

解决方案B 你甚至可以做一个函数,让生活更轻松

def findKeyValue(alphabet, key, index):
    return alphabet.find(key[index].__str__())
然后

if mode == 'encrypt':
    num += findKeyValue(LETTERS, key, keyIndex)
elif mode == 'decrypt':
    num -= findKeyValue(LETTERS, key, keyIndex)

可能将其更改为num+=strleters.findkey[keyIndex]或num+='{}.formatLETTERS.findkey[keyIndex]顺便说一句,OTP可以实现得非常紧凑,比如:在izimpessage中,print.joinchrordx^ordy代表x,y,键假设来自itertools导入*。嘿,Polywhill先生,我尝试了你的两个答案,但我得到了相同的错误:TypeError:无法将'int'对象隐式转换为str ID您在第72行也会得到一个错误,因为您必须执行相同的操作。我没有看到代码的这一部分。错误出现在第70行。我还尝试对第70行和第72行执行相同的操作。还在error@JaiminN当前位置我发现了问题。我用蟒蛇32做了这个。
            if mode == 'encrypt':
                num += int(LETTERS.find(key[keyIndex])) # Add if encrypting
            elif mode == 'decrypt':
                num -= int(LETTERS.find(key[keyIndex])) # Subract if decrypting
if mode == 'encrypt':
    num += LETTERS.find(str(key[keyIndex]))
elif mode == 'decrypt':
    num -= LETTERS.find(str(key[keyIndex]))
def findKeyValue(alphabet, key, index):
    return alphabet.find(key[index].__str__())
if mode == 'encrypt':
    num += findKeyValue(LETTERS, key, keyIndex)
elif mode == 'decrypt':
    num -= findKeyValue(LETTERS, key, keyIndex)