[Solved] 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"

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

Solution #1:

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.

Respondent: user2441441

Solution #2:

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

f = mystring.replace("'","").replace('"', '')
Respondent: Malik Brahimi

Solution #3:

This is what finally worked for my situation.

#Python 2.7
import string

companyName = string.replace(companyName, "'", "")
Respondent: Avinash Raj

Solution #4:

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”

Respondent: Steven Kritzer

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.