Chuvi
Chuvi

Reputation: 1298

Python Substring replacement

i need to replace the substring in the main string

mainstr='"Name":"xxx","age":"{"This":"has to","be":"replaced"}","dept":"cse"'
substr='"{"This":"has to","be":"replaced"}"'

Desired output:

mainstr="Name:xxx","age":"checked","dept":"cse"

I tried the following code:

for substr in mainstr:

    mainstr=mainstr.replace(substr,"checked")
    print "Output=",mainstr

On executing i got,

Output="Name:xxx","age":"{This":"has to","be":"replaced"}","dept":"cse"   

Why the substr not getting replaced??..

Upvotes: 1

Views: 305

Answers (1)

TerryA
TerryA

Reputation: 60024

You're iterating through the string, which isn't doing what you'd expect. Iterating through a string goes through each character.

All you need to do is:

mainstr = '"Name:xxx","age":"{This":"has to","be":"replaced"}","dept":"cse"'
substr = '{This":"has to","be":"replaced"}'
print "Output = ", mainstr.replace(substr, 'checked')
#                ^ The comma here is important.

NOTE: The code isn't working for you because substr = '"{This and not substr = '{This". Notice the quotation mark at the beginning.

Upvotes: 4

Related Questions