1

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

2
  • 2
    Please fix the apostrophe markings in your question so it actually is a string :) Commented Nov 18, 2013 at 7:23
  • 1
    it's not strings actually. vote to close Commented Nov 18, 2013 at 7:25

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@harido: MAy be my mistake in rest part of the pgm.. will check it out.... thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.