Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to ignore string in quotes for python replace()?

Is it possible to ignore string in quotes for python replace()?
I have a string variable like this:

a = "I like bananas 'I like bananas'"

I want to get a result like this via replace():

"I like apples 'I like bananas'".

But when I execute print(a.replace("bananas", "apples")),the result is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"I like apples 'I like apples'".

How can I do to make replace() ignore string in quotes?

>Solution :

Split the string by ‘, process only the odd elements of the array, reassemble the string

a = "I like bananas 'I like bananas'"
ap = a.split("'")
ar = [ ai.replace("bananas", "apples")  if i%2==0 else ai for i,ai in enumerate(ap)]
print("'".join(ar))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading