错误:“str”对象不支持项目分配python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24892777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:25:17  来源:igfitidea点击:

Error: 'str ' object does not support item assignment python

pythonpython-2.7

提问by user3510057

Error: 'str ' object does not support item assignment python

错误:“str”对象不支持项目分配python

dict=['A', 'a','B', 'b','C', 'c','D', 'd','E', 'e','F', 'f','G', 'g','H', 'h','I',       'i','J', 'j','K', 'k','L', 'l','M', 'm','N', 'n','P', 'o','P', 'p','Q', 'q','R', 'r','S',                   's','T', 't','U', 'u','V', 'v','W', 'w','X', 'x','Y', 'y','Z' 'z']

def cript(s):
    for i in range(0,len(s)):
        a=dict.index(s[i])
        if a<26:
            s[i]=dict[a+26]
        else:
            s[i]=dict[a-26]
    return s

print cript('Hello')

Error line 6

错误行 6

    s[i]= dict[a+26]
TypeError: 'str' object does not support item assignment python

采纳答案by TheSoundDefense

Python does not allow you to swap out characters in a string for another one; strings are immutable. What you'll need to do is create a totally different string and return that instead.

Python 不允许您将一个字符串中的字符替换为另一个;字符串是不可变的。您需要做的是创建一个完全不同的字符串并返回它。

dict=['A', 'a','B', 'b','C', 'c','D', 'd','E', 'e','F', 'f','G', 'g','H', 'h','I', 'i','J', 'j','K', 'k','L', 'l','M', 'm','N', 'n','P', 'o','P', 'p','Q', 'q','R', 'r','S', 's','T', 't','U', 'u','V', 'v','W', 'w','X', 'x','Y', 'y','Z' 'z']

def cript(s):
    crypt_s = ""
    for i in range(0,len(s)):
        a=dict.index(s[i])
        if a<26:
            crypt_s += dict[a+26]
        else:
            crypt_s += dict[a-26]
    return crypt_s

print cript('Hello')

Of course, there may be other issues with the code, but that will solve that specific error message.

当然,代码可能还有其他问题,但这将解决该特定错误消息。

回答by Dannnno

Strings are immutable objects, meaning they can't be modified in place (you'd have to return a new string and reassign it).

字符串是不可变对象,这意味着它们不能就地修改(您必须返回一个新字符串并重新分配它)。

s[i] = dict[a + 26] 

is trying to reassign a value in the string

正在尝试重新分配字符串中的值

Here is an easier to see example

这是一个更容易看到的例子

>>> astring = "Hello"
>>> astring[0] = "a"

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    astring[0] = "a"
TypeError: 'str' object does not support item assignment

回答by Omar Tahri

def game():
    list = ["pomme", "anniversaire", "table", "travail", "amies", "enfants"]
    ran = random.randint(0, (len(list)-1)/2)
    mot = list[ran]
    length = len(mot)
    for x in range(0, length-1):
        if length % 2 ==0:
            a = int(random.randint(-length/2, length/2))
        else:
            a = int(random.randint(-(length-1)/2, (length-1)/2))
        mot[x] = mot[x+a]