Javatpoint Logo
Javatpoint Logo

How to Remove Single Quotes from Strings in Python

In this tutorial, we will learn how to remove single quotes from the string. Sometimes, we must remove all sections or just the ones surrounding a string. We can also remove the single and double quotes. We will use various methods to remove quotes; you can use any of them, which is totally up to the user.

Let's have an example string with three double quotation marks.

We will use several methods to remove all "from the example string.

We will use the several methods to remove all " from the example string.

Using replace() method

The str.replace() method takes the two arguments - string we want to replace and replacement string. In this case, we will replace the double quotation mark (") with the empty string. Let's understand the following example.

Example -

Output:

This is a string with quotes

Regular Expression

We can use regular expressions to remove all quotes from a string. Before we start using regular expressions in Python, we first need to import the re module. Let's understand the following example.

Example -

Output:

This is a string with quotes

We get the new string without any quotes in it.

str.join()

This method is also helpful in removing all quotes from a string in Python. This solution has a more complex syntax than other solutions, and it looks at each character of the given string and appends each, which is not a quotation mark to the empty string.

Example -

Output:

This is a string with quotes

How to Remove Quotes Surrounding a String

In the previous sections, we discussed many ways to remove quotes from the string. But there is a more common problem, how to remove only quotes surrounding a string. The str.strip() method is intended to perform such an operation.

Let's take example_str from the previous section, and remove the quotation mark using the strip() method.

Example -

Output:

This is a string" with quotes

The strip() method removes the leading and trailing quotation marks from the example_str.

The strip() also comes with the two derivatives methods - str.lstrip() and str.rstrip(). The first one removes all leading quotes, and the second removes all trailing quotes.

Example -

Output:

This is a string" with quotes"
"This is a string" with quotes

Conclusion

This tutorial included the various ways to remove quotes from a string in Python. First, we explained how to remove all quotes from a string using several different methods - str.replace(), str.join() and re.sub(). Then, we explained the str.strip() method, as well as its derivatives str.lstrip() and rstrip().







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA