'str'对象不支持Python中的项目分配


130

我想从字符串中读取一些字符,然后将其放入其他字符串中(就像我们在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中,代码可能是

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

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


19
顺便说一句,不要以python内置函数命名您的变量。如果您str在此处用作变量,则将无法使用进行字符串转换str(var_that_is_not_a_string)或键入诸如的比较type(var_with_unknown_type) == str
乔尔·科内特

Answers:


100

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

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

for i in str:
    srr += i

起作用的原因是它是以下操作的快捷方式:

for i in str:
    srr = srr + i

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


然后,如果我要从字符串中读取字符并将它们复制到某些位置,那我该怎么做?
Rasmi Ranjan Nayak 2012年

1
@RasmiRanjanNayak:这取决于您需要使用那些字符。在我的回答中,我展示了如何将它们附加到另一个字符串。
NPE

我想编写一个程序“ Hello world”到“ World Hello”。因此,我的代码应搜索空格('')。所以我一直在寻找帮助
Rasmi Ranjan Nayak 2012年

5
@RasmiRanjanNayak:print " ".join(reversed("Hello world".split())).capitalize()
乔尔·科内特

2
@aix:距离实际上只有几秒钟。:D
乔尔·科内特

113

其他答案是正确的,但是您当然可以执行以下操作:

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

如果您真的想要。


14

Python字符串是不可变的,因此您在C语言中尝试执行的操作在python中根本不可能实现。您将必须创建一个新字符串。

我想从字符串中读取一些字符,然后将其放入其他字符串中。

然后使用字符串切片:

>>> s1 = 'Hello world!!'
>>> s2 = s1[6:12]
>>> print s2
world!

5

如aix所述-Python中的字符串是不可变的(您不能就地更改它们)。

您要尝试执行的操作可以通过多种方式完成:

# Copy the string

foo = 'Hello'
bar = foo

# Create a new string by joining all characters of the old string

new_string = ''.join(c for c in oldstring)

# Slice and copy
new_string = oldstring[:]

1

如果您想将特定字符换成另一个字符,则可以采用另一种方法:

def swap(input_string):
   if len(input_string) == 0:
     return input_string
   if input_string[0] == "x":
     return "y" + swap(input_string[1:])
   else:
     return input_string[0] + swap(input_string[1:])

0

该解决方案如何:

str =“ Hello World”(如问题所述)srr = str +“”


-2

嗨,您应该尝试使用字符串拆分方法:

i = "Hello world"
output = i.split()

j = 'is not enough'

print 'The', output[1], j
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.