‘str’ object does not support item assignment in Python

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] != '')
{
srr[j++] = str [i++];
}

How can I implement the same in Python?

7 Answers

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.

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 to.

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!

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

Another approach if you wanted to swap out a specific character for another character:

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

How about this solution:

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

Hi you should try the string split method:

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

j = 'is not enough'

print 'The', output[1], j

Leave a Reply

Your email address will not be published. Required fields are marked *