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?
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:])
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!
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.
How about this solution:
str="Hello World" (as stated in problem) srr = str+ ""
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[:]
Hi you should try the string split method:
i = "Hello world"
output = i.split()
j = 'is not enough'
print 'The', output[1], j
Source: Stackoverflow.com