【发布时间】:2012-05-17 07:18:41
【问题描述】:
我想从字符串s1 中读取一些字符并将其放入另一个字符串s2。
但是,分配给s2[j] 会出错:
s2[j] = s1[i]
# TypeError: 'str' object does not support item assignment
在 C 中,这是可行的:
int i = j = 0;
while (s1[i] != '\0')
s2[j++] = s1[i++];
我在 Python 中的尝试:
s1 = "Hello World"
s2 = ""
j = 0
for i in range(len(s1)):
s2[j] = s1[i]
j = j + 1
【问题讨论】:
-
顺便说一句,不要在 python 内置函数之后命名你的变量。如果在这里使用
str作为变量,您将无法使用str(var_that_is_not_a_string)进行字符串转换或键入type(var_with_unknown_type) == str等比较。 -
查看stackoverflow.com/questions/41752946/… 修复
TypeError: 'str' object does not support item assignment。 -
这对 Python 来说确实是一个负数