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.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With