不可变字符串,typeerror:'str'对象不支持项目赋值

时间:2017-10-06 13:55:04

标签: python-3.x

我正在使用别人的代码制作一个密码求解器,但它给了我

typeerror: 'str' object does not support item assignment"

key[keyIndex] = cipherletter

有没有办法与错误保持相同的含义? :)

def decryptWithCipherletterMapping(ciphertext, letterMapping):
# Return a string of the ciphertext decrypted with the letter mapping,
# with any ambiguous decrypted letters replaced with an _ underscore.

# First create a simple sub key from the letterMapping mapping.
    key = ['x'] * len(LETTERS)
    for cipherletter in LETTERS:
        if len(letterMapping[cipherletter]) == 1:
# If there's only one letter, add it to the key.
            keyIndex = LETTERS.find(letterMapping[cipherletter][0])
            key[keyIndex] = cipherletter
        else:
            ciphertext = ciphertext.replace(cipherletter.lower(), '_')
            ciphertext = ciphertext.replace(cipherletter.upper(), '_')
            key = ''.join(key)

# With the key we've created, decrypt the ciphertext.

return simpleSubCipher.decryptMessage(key, ciphertext)

2 个答案:

答案 0 :(得分:1)

因为key的类型为str

在Python中,字符串不支持像列表一样的项目赋值(如明确说明的错误消息)。

要将字符串的字符更新为给定索引,您可以执行以下操作:

string = "foobar"
charindex = 2 # so you wants to replace the second "o"
print(string[0:charindex] + 'O' + string[charindex+1:])
# gives foObar

或者将其转换为功能:

def replace_at_index(string, replace, index):
    return string[0:index] + replace + string[index+1:]

print(replace_at_index('EggsandBacon', 'A', 4))
# gives EggsAndBacon

所以你会像以下一样使用它:

key = replace_at_index(key, cipherletter, keyIndex)

答案 1 :(得分:1)

简短的回答是你有一个缩进错误。而不是:

# First create a simple sub key from the letterMapping mapping.
    key = ['x'] * len(LETTERS)
    for cipherletter in LETTERS:
        if len(letterMapping[cipherletter]) == 1:
# If there's only one letter, add it to the key.
            keyIndex = LETTERS.find(letterMapping[cipherletter][0])
            key[keyIndex] = cipherletter
        else:
            ciphertext = ciphertext.replace(cipherletter.lower(), '_')
            ciphertext = ciphertext.replace(cipherletter.upper(), '_')
            key = ''.join(key)

你应该:

# First create a simple sub key from the letterMapping mapping.
keyList = ['x'] * len(LETTERS)

for cipherletter in LETTERS:
    if len(letterMapping[cipherletter]) == 1:
        # If there's only one letter, add it to the key.
        keyIndex = LETTERS.find(letterMapping[cipherletter][0])
        keyList[keyIndex] = cipherletter
    else:
        ciphertext = ciphertext.replace(cipherletter.lower(), '_')
        ciphertext = ciphertext.replace(cipherletter.upper(), '_')

key = ''.join(keyList)

更深层次的问题是,您在原始代码中使用key 字符串列表。显然这令人困惑,见证了你最终感到困惑的事实!在我上面的版本中,我将它们分成两个不同的变量,我认为你会发现它们更清楚。