我想从字符串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中的字符串是不可变的(你不能就地更改它们)。

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

复制字符串:

foo = 'Hello'
bar = foo

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

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

切片和复制:

new_string = oldstring[:]

其他回答

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

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

如果你真的想的话。

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

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

复制字符串:

foo = 'Hello'
bar = foo

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

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

切片和复制:

new_string = oldstring[:]

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

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

j = 'is not enough'

print 'The', output[1], j

给s2[j]赋值会出错

字符串是不可变的,所以你在C中所做的在Python中是不可能的。相反,您必须创建一个新的字符串。

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

用切片:

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

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

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