Skip to content

Python remove single quotes from a string | (‘)

  • by

You can remove single quotes from a string in python using replace the function or translate function, Regular Expressions, etc.

A easiest way is just replace the apostrophe character with an empty string:

msg = "Hell'o"
print(msg.replace("'", ""))

Way to remove single quotes from a string in Python

Examples

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

1. replace() function (str.replace)

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

msg = "A single 'char'".replace("'", "")
print(msg)

Output: A single char

2. translate() function (str.translate)

This method is used in Python 2, To remove characters you can pass the first argument to the function with all the substrings to be removed as second.

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

In Python 3

You will have to use str.maketrans

3. Regular Expressions using re

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.

You have to import a module in python.

import re

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

4. Other ways – remove single quotes in Python

Using list call along with remove and join. But it will remove only first occurrence of single quote.

str = "Hello' ' word"
x = list(str)
x.remove("'")
print(''.join(x))

Output: Hello ‘ word

Do comment if you know any other way to do it, doubts and suggestion on this tutorial.

Note: This example (Project) is developed in PyCharm 2020.1 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.15.4
Python 3.7
All Python Programs code are in Python 3, so it may change its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading