'str' object does not support item assignment in Python

匿名 (未验证) 提交于 2019-12-03 01:48:02

问题:

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

So my code is like below

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) 

In C the code may be

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

How can I implement the same in Python?

回答1:

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 

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



回答2:

The other answers are correct, but you can, of course, do something like:

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

if you really want to.



回答3:

Python strings are immutable so what you are trying to do in C will be simply impossible in python. You will have to create a new string.

I would like to read some characters from a string and put it into other string.

Then use a string slice:

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


回答4:

As aix mentioned - strings in Python are immutable (you cannot change them inplace).

What you are trying to do can be done in many ways:

# 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[:] 


回答5:

How about this solution:

str="Hello World" (as stated in problem) srr = str+ ""



回答6:

Hi you should try the string split method:

i = "Hello world" output = i.split()  j = 'is not enough'  print 'The', output[1], j 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!