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

当前回答

嗨,你应该尝试字符串分割方法:

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

j = 'is not enough'

print 'The', output[1], j

其他回答

这个解决方案怎么样:

str="Hello World"(如问题中所述) SRR = str+ ""

Python中的字符串是不可变的(你不能就地更改它们)。

你想做的事情可以通过很多方式来实现:

复制字符串:

foo = 'Hello'
bar = foo

通过连接旧字符串的所有字符创建一个新字符串:

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

切片和复制:

new_string = oldstring[:]

其他答案将字符串转换为列表或逐字符构造新字符串。这些方法可能代价很高,特别是对于大字符串。相反,我们可以使用切片来获得被更改字符之前和之后的字符串部分,并将它们与新字符结合起来。

在这里,我修改了Crowman回答中的示例代码,使用字符串切片替换字符串中的单个字符,而不是转换为列表。

>>> str1 = "mystring"
>>> pos = 5
>>> new_char = 'u'
>>> str2 = str1[:pos] + new_char + str1[pos+1:]
>>> print(str2)
mystrung
>>> type(str2)
<class 'str'>

如果你想把一个特定的字符换成另一个字符,另一种方法是:

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:])

嗨,你应该尝试字符串分割方法:

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

j = 'is not enough'

print 'The', output[1], j