Home > Software engineering >  Is it possible to ignore string in quotes for python replace()?
Is it possible to ignore string in quotes for python replace()?

Time:03-17

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?

CodePudding user response:

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

CodePudding user response:

No, it is not possible, you cannot make replace ignore those matches. You will have to code your own solution.

CodePudding user response:

You can use count value (optional parameter of the replace method) to specify how many occurrences of the old value you want to replace. It works fine for both.

a = "I like bananas \"I like bananas\""
print(a.replace("bananas", "apples",1))

a = "I like bananas 'I like bananas'" 
print(a.replace("bananas", "apples",1))

Output:

I like apples 'I like bananas'
  • Related