w=""
q=""
while 1:
if x>=len(b) or y>=len(a):
break
if s[x][y]=="\\":
w=w+a[y]
q=s[x]
q[y]="_"
s[x]=q
x=x+1
y=y+1
else:
return w
break
其中s[]是一个列表,每个列表项都是字符串。
但运行后编译器提示错误:
q[y]="_"
TypeError: 'str' object does not support item assignment
请问该如何解决?
最近我在学python语言,这个是想在w=w+a[y]之后,把s[x][y]的值从"\\"改成"_"
确实没贴完,但我只是想问一下字符串的问题。
追答如果你说是字符串的问题,那是想用索引的方法去改变字符串。这样是不可取的,字符串是不可变的对象,相对于可变对象就比如列表 。你看一下实验:
>>> s='look me'
>>> s[4]
' '
>>> s[2]
'o'
>>> s[4]='+'
Traceback (most recent call last):
File "", line 1, in
s[4]='+'
TypeError: 'str' object does not support item assignment
>>> s[2]='del'
Traceback (most recent call last):
File "", line 1, in
s[2]='del'
TypeError: 'str' object does not support item assignment
>>>
>>> l=[1,2,3]
>>> l
[1, 2, 3]
>>> l[1]='a'
>>> l
[1, 'a', 3]
>>>
看到了吧,对字符串进行索引赋值时就会引发
TypeError: 'str' object does not support item assignment
再说一次,字符串是不可变的,不能这样操作,但对列表索引赋值时就没有问题