Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace (not remove) a character with condition

Tags:

python

regex

How do I use the replace function to replace all instances with the exception of one.

mystr = "he said: 'hi my name's Jim'."
mystr.replace("'", '"')
print(mystr)

The output I would want is: he said: "hi my name's Jim".

How do I exclude 's from the replace? ie exclude all ' followed by an s and where the ' is preceded by digit/letter.

if mystr2 = "'s: hi'" then I wouldn't want to replace the first ' only replace the second '.

UPDATE Removing single quotes if they aren't in the middle of a word This shows how to remove the required quotes, but not how to replace it.

like image 759
alwayscurious Avatar asked Sep 05 '26 19:09

alwayscurious


1 Answers

Better approach would be to use this regex:

\B'\b|\b'\B

and replace with ".

RegEx Demo

  • \b: Word boundary
  • \B: inverse of \b or word boundary
>>> import re
>>> mystr = "he said: 'hi my name's Jim'."
>>> print (re.sub(r"\B'\b|\b'\B", '"', mystr))
he said: "hi my name's Jim".
like image 140
anubhava Avatar answered Sep 07 '26 08:09

anubhava