Python で str object does not support item assignment エラーを修正

Haider Ali 2022年4月14日
Python で str object does not support item assignment エラーを修正

Python では、文字列は不変であるため、文字列を変更しようとすると、str object does not support item assignment というエラーが発生します。

文字列の現在の値を変更することはできません。完全に書き直すか、最初にリストに変換することができます。

このガイド全体は、このエラーの解決に関するものです。飛び込みましょう。

Python で str object does not support item assignment エラーを修正

文字列は不変であるため、そのインデックスの 1つに新しい値を割り当てることはできません。次のコードを見てください。

# 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 を返し、後で新しい値が 4 番目のインデックスに割り当てられるとエラーを出します。

文字列は単一の値として機能します。インデックスはありますが、個別に値を変更することはできません。ただし、最初にこの文字列をリストに変換すると、その値を更新できます。

# 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