修復 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