修复 Python 中的 str 对象不支持项分配错误

Haider Ali 2022年5月18日
修复 Python 中的 str 对象不支持项分配错误

在 Python 中,字符串是不可变的,因此在尝试更改字符串时,我们会得到 str object does not support item assignment 错误。

你不能对字符串的当前值进行一些更改。你可以完全重写它,也可以先将其转换为列表。

整个指南都是关于解决这个错误的。让我们深入了解一下。

修复 Python 中的 str object does not support item assignment 错误

由于字符串是不可变的,我们不能为其索引之一分配新值。看看下面的代码。

# String Variable
string = "Hello Python"

# printing Fourth index element of the String
print(string[4])

# Trying to Assign value to String
string[4] = "a"

上面的代码将给出 o 作为输出,稍后一旦将新值分配给它的第四个索引,它将给出错误。

字符串作为单个值工作;虽然它有索引,但你不能单独更改它们的值。但是,如果我们先将此字符串转换为列表,我们可以更新它的值。

# String Variable
string = "Hello Python"

# printing Fourth index element of the String
print(string[4])

# Creating list of String elements
lst = list(string)
print(lst)

# Assigning value to the list
lst[4] = "a"
print(lst)

# use join function to convert list into string
new_String = "".join(lst)

print(new_String)

输出:

o
['H', 'e', 'l', 'l', 'o', ' ', 'P', 'y', 't', 'h', 'o', 'n']
['H', 'e', 'l', 'l', 'a', ' ', 'P', 'y', 't', 'h', 'o', 'n']
Hella Python

上面的代码将完美运行。

首先,我们创建一个字符串元素列表。与列表中一样,所有元素都由它们的索引标识并且是可变的。

我们可以为列表的任何索引分配一个新值。稍后,我们可以使用 join 函数将同一个列表转换为字符串,并将其值存储到另一个字符串中。

作者: Haider Ali
Haider Ali avatar Haider Ali avatar

Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.

LinkedIn

相关文章 - Python Error