5

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?

user2441441
  • 1,235
  • 4
  • 23
  • 39

4 Answers4

17

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.

Malik Brahimi
  • 15,933
  • 5
  • 33
  • 65
3

Strings are immutable in python. So can't do an in-place replace.

f = mystring.replace("'","").replace('"', '')
print(f)
Avinash Raj
  • 166,785
  • 24
  • 204
  • 249
0

This is what finally worked for my situation.

#Python 2.7
import string

companyName = string.replace(companyName, "'", "")
-1

Using regular expression is the best solution

import re
REPLACE_APS = re.compile(r"[\']")

text = " 'm going"
text = REPLACE_APS .sub("", text)

input = " 'm going" output = " m going"

GpandaM
  • 39
  • 4