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:
"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))