本文介绍了“str"对象不支持项目分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从字符串 s1
中读取一些字符并将其放入另一个字符串 s2
.
I would like to read some characters from a string s1
and put it into another string s2
.
然而,赋值给 s2[j]
会报错:
However, assigning to s2[j]
gives an error:
s2[j] = s1[i]
# TypeError: 'str' object does not support item assignment
在 C 中,这是有效的:
In C, this works:
int i = j = 0;
while (s1[i] != '\0')
s2[j++] = s1[i++];
我在 Python 中的尝试:
My attempt in Python:
s1 = "Hello World"
s2 = ""
j = 0
for i in range(len(s1)):
s2[j] = s1[i]
j = j + 1
推荐答案
在 Python 中,字符串是不可变的,因此您无法就地更改其字符.
In Python, strings are immutable, so you can't change their characters in-place.
但是,您可以执行以下操作:
You can, however, do the following:
for c in s1:
s2 += c
这样做的原因是它是一个快捷方式:
The reasons this works is that it's a shortcut for:
for c in s1:
s2 = s2 + c
上面的每次迭代都会创建一个新字符串,并将对该新字符串的引用存储在s2
中.
The above creates a new string with each iteration, and stores the reference to that new string in s2
.
这篇关于“str"对象不支持项目分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!