'Str' object does not support element assignment in Python

I would like to read some characters from a string and put it on another string (as in C).

So my code looks 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 could be

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

How can I implement the same in Python?

+55
python string
May 17 '12 at 7:18
source share
6 answers

In Python, strings are immutable, so you cannot change their characters in place.

You can, however, do the following:

 for i in str: srr += i 

Reasons for this: this is a shortcut to:

 for i in str: srr = srr + i 

The above procedure creates a new line with each iteration and stores the link to this new line in srr .

+46
May 17 '12 at 7:19
source share

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) <type 'str'> 

if you really want it.

+44
Aug 01 '13 at 23:44
source share

Python strings are immutable, so what you're trying to do in C will just be impossible in python. You will need to create a new line.

I would like to read some characters from a string and put it on another string.

Then use the string fragment:

 >>> s1 = 'Hello world!!' >>> s2 = s1[6:12] >>> print s2 world! 
+6
May 17 '12 at 7:23
source share

As mentioned above, strings in Python are immutable (you cannot change them in place).

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[:] 
+4
May 17 '12 at 7:24 a.m.
source share

How about this solution:

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

-one
Aug 01 '13 at 22:16
source share

Hi, you should try the line splitting method:

 i = "Hello world" output = i.split() j = 'is not enough' print 'The', output[1], j 
-3
Jan 01 '15 at 21:52
source share



All Articles