Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing unquoted words only in Python

Tags:

python

I am looking for a way to replace a word, however only when its not surounded by quotations.

For example Replacing Hello with Hi

Hello 'Hello' NothingHi 'Hello' Nothing

Since 'Hello' is in quotes it does not get replaced, but the first Hello does because it is not wrapped with quotes.

Any help would be great!

like image 494
user1357159 Avatar asked Jan 01 '26 23:01

user1357159


1 Answers

Regular expressions are awesome:

>>>import re

>>>expression = re.compile("(?!(\"|'))Hello(?!(\"|'))")
>>>expression.sub("Hi",'This string says "Hello" and Hello')

This string says "Hello" and Hi

The only problem with that is that it will also fail to replace "Hello and Hello", if that becomes an issue you can add specific cases for them.

like image 98
Josiah Avatar answered Jan 03 '26 12:01

Josiah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!