错误:'str'对象不支持项目赋值python

时间:2014-07-22 16:25:39

标签: python python-2.7

错误:'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')

错误第6行

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

3 个答案:

答案 0 :(得分:4)

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')

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

答案 1 :(得分:2)

字符串是不可变对象,意味着它们无法在适当的位置进行修改(您必须返回一个新字符串并重新分配)。

s[i] = dict[a + 26] 

正在尝试重新分配字符串

中的值

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

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

答案 2 :(得分:0)

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]