Replace the single quote (') character from a string

Question:

I need to strip the character "'" from a string in python. How do I do this?

I know there is a simple answer. Really what I am looking for is how to write ' in my code. for example n = newline.

Asked By: Richard

||

Answers:

As for how to represent a single apostrophe as a string in Python, you can simply surround it with double quotes ("'") or you can escape it inside single quotes (''').

To remove apostrophes from a string, a simple approach is to just replace the apostrophe character with an empty string:

>>> "didn't".replace("'", "")
'didnt'
Answered By: Mark Rushakoff

Do you mean like this?

>>> mystring = "This isn't the right place to have "'" (single quotes)"
>>> mystring
'This isn't the right place to have "'" (single quotes)'
>>> newstring = mystring.replace("'", "")
>>> newstring
'This isnt the right place to have "" (single quotes)'
Answered By: sberry

You can escape the apostrophe with a character as well:

mystring.replace(''', '')

Here are a few ways of removing a single ' from a string in python.

  • str.replace

    replace is usually used to return a string with all the instances of the substring replaced.

    "A single ' char".replace("'","")
    
  • str.translate

    In Python 2

    To remove characters you can pass the first argument to the funstion with all the substrings to be removed as second.

    "A single ' char".translate(None,"'")
    

    In Python 3

    You will have to use str.maketrans

    "A single ' char".translate(str.maketrans({"'":None}))
    
  • re.sub

    Regular Expressions using re are even more powerful (but slow) and can be used to replace characters that match a particular regex rather than a substring.

    re.sub("'","","A single ' char")
    

Other Ways

There are a few other ways that can be used but are not at all recommended. (Just to learn new ways). Here we have the given string as a variable string.

Another final method can be used also (Again not recommended – works only if there is only one occurrence )

  • Using list call along with remove and join.

    x = list(string)
    x.remove("'")
    ''.join(x)
    
Answered By: Bhargav Rao

I met that problem in codewars, so I created temporary solution

pred = "aren't"
pred = pred.replace("'", "99o")
pred = pred.title()
pred = pred.replace("99O", "'")
print(pred)

You can use another char combination, like 123456k and etc., but the last char should be letter

Answered By: 0xblvck
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.