修复 Python 中的 str 对象不支持项分配错误
在 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 函数将同一个列表转换为字符串,并将其值存储到另一个字符串中。
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串