169
votes

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?

7
Btw, don't name your variables after python builtins. If you use str as a variable here, you will be unable to do string conversions with str(var_that_is_not_a_string) or type comparisions such as type(var_with_unknown_type) == str. - Joel Cornett
See stackoverflow.com/questions/41752946/… to fix TypeError: 'str' object does not support item assignment. - Friedrich

7 Answers

121
votes

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.

141
votes

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.

21
votes

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!
6
votes

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

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

How about this solution:

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

0
votes

Hi you should try the string split method:

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

j = 'is not enough'

print 'The', output[1], j