python - “str”对象不支持项目分配

标签 python string

我想从字符串 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

最佳答案

其他答案都是正确的,但你当然可以这样做:

>>> str1 = "mystring"
>>> list1 = list(str1)
>>> list1[5] = 'u'
>>> str1 = ''.join(list1)
>>> print(str1)
mystrung
>>> type(str1)
<type 'str'>

如果你真的想的话。

关于python - “str”对象不支持项目分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10631473/

相关文章:

python - 每隔一个数字加 1

c# - 获取 <> 之间的值,其中包含动态数字

ios - 使用单个 RegEx 匹配字符串的变体

python - 如何通过opencv匹配纸张

python - 通过复制到目录在 Mac 上安装 Django?

Python:ftp 和进度条 2.3

javascript - jquery ":contains"选择器是否接受这种值 "Banking and Finance"?

c - 在 K&R C 中传递字符串文字

python - 获取整数中偶数最长序列的最佳方法

python - 重新创建字符级RNN以生成文本