user2441441 user2441441 - 4 months ago 17
Python Question

Python remove all apostrophes from a string

I wanted to remove all occurrences of single and double apostrophes in lots of strings.

I tried this-

mystring = "this string shouldn't have any apostrophe - \' or \" at all"
print(mystring)
mystring.replace("'","")
mystring.replace("\"","")
print(mystring)


It doesn't work though! Am I missing something?

Answer

Replace is not an in-place method, meaning it returns a value that you must reassign.

mystring = mystring.replace("'", "")
mystring = mystring.replace('"', "")

In addition, you can avoid escape sequences by using single and double quotes like so.