Python 报错:‘str‘ object does not support item assignment 将string转换为list可解决

# string 转 list 代码
s = "23"
s = list(s)
print(s)

# 输出
['2', '3']

由于python 中 string不支持使用访问index的方式改变值,所以可以先将其转换为list,在进行值的修改

# 错误代码

s = "23"
s[1] = "a"
print(s[1])

#报错信息
'str' object does not support item assignment

# 转list的解决方法
s = "23"
s = list(s)
s[1] = "a"
s = "".join(s)
print(s)

#返回值
"2a"

你可能感兴趣的:(Python,python,list,leetcode)