7

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,237
  • 4
  • 24
  • 45

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
  • 16,341
  • 7
  • 39
  • 70
3

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

f = mystring.replace("'","").replace('"', '')
print(f)
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
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
  • 47
  • 4