Replacing unquoted words only in Python

后端 未结 6 856
情深已故
情深已故 2021-01-21 04:03

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

For example Replacing Hello with Hi

6条回答
  •  春和景丽
    2021-01-21 04:31

    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.

提交回复
热议问题