'str' 对象不支持 Python 中的项目分配 [英] 'str' object does not support item assignment in Python

查看:49
本文介绍了'str' 对象不支持 Python 中的项目分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个字符串中读取一些字符并将其放入另一个字符串中(就像我们在 C 中所做的那样).

I would like to read some characters from a string and put it into other string (Like we do in C).

所以我的代码如下

import string
import re
str = "Hello World"
j = 0
srr = ""
for i in str:
    srr[j] = i #'str' object does not support item assignment 
    j = j + 1
print (srr)

在 C 中,代码可能是

In C the code may be

i = j = 0; 
while(str[i] != '\0')
{
srr[j++] = str [i++];
}

如何在 Python 中实现相同的功能?

How can I implement the same in Python?

推荐答案

在 Python 中,字符串是不可变的,因此您无法就地更改其字符.

In Python, strings are immutable, so you can't change their characters in-place.

但是,您可以执行以下操作:

You can, however, do the following:

for i in str:
    srr += i

这样做的原因是它是一个快捷方式:

The reasons this works is that it's a shortcut for:

for i in str:
    srr = srr + i

上面的每次迭代都会创建一个新字符串,并将对该新字符串的引用存储在srr中.

The above creates a new string with each iteration, and stores the reference to that new string in srr.

这篇关于'str' 对象不支持 Python 中的项目分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆