原始代码简化如下:
dbname="dbname|mysqldb" print(dbname[6]) dbname[6]="#" print(dbname[6])
运行结果如下:
C:\Users\warms\PycharmProjects\untitled\venv\Scripts\python.exe C:/Users/warms/PycharmProjects/untitled/a.py | Traceback (most recent call last): File "C:/Users/warms/PycharmProjects/untitled/a.py", line 5, in dbname[6]="#" TypeError: 'str' object does not support item assignment Process finished with exit code 1
原因分析:
在Python语言中,字符串String类型为不可变的数据类型。所以对其值进行修改时,会报不支持此种操作的错误。像整型int、浮点型float、字符串型string和元组tuple,都是不可变数据类型。而像列表list和字典dict属于可变数据类型,其子元素的值是可以改变的。