replace (not remove) a character with condition

Viewed 144

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.

2 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".

another regex: '(?!s) replaces every ' that is not followed by a s

import re
mystr = "he said: 'hi my name's Jim'."
newstr = re.sub(r"'(?!s)", '"', mystr)
print(newstr)

output: he said: "hi my name's Jim".

Related