Home » Python » Remove Quotes from a String in Python

Remove Quotes from a String in Python

To remove quotes from a string in Python, use str.replace(oldValue,newValue) to find occurrences of double quotes (“) and replace them with “”.

str.replace() in Python replaces the specified phrase in the string with the new phrase. Use the replace() method for eliminates quotes from a string in Python. For example, removing all quotes from a string ‘”‘ with ”

In this example, we will discuss how to use the str.replace() in Python to remove quotes from a string and str.strip() method for stripping quotes from a string in Python.

Use str.replace() to remove quotes from a string in Python

To remove quotes from a string in Python using replace():

  1. Call the str.replace() on a string and pass a ‘”‘ to search for and a new character space ‘ ‘ for a replacement.
  2. The replace() returns a copy of the string in which all occurrences of double quotes are replaced by a new character (space) ”.
str = '"Hi!" "Welcome to Python Programming"'

str1 = str.replace('"','')
print(str1)

In the above Python program, we pass the following parameters to replace():

  1. str variable stores the string that contains double quotes.
  2. Use str.replace() to remove quotes in a string.
  3. character ‘”‘ to search for in the string.
  4. replacement character ‘ ‘ (space). It will replace all occurrences of quotes ‘”‘ with ‘ ‘

It will return the copy of the string and store it in the str1 variable and print using print() Python.

The output of the above program after removing quotes in a string with a space in Python is:

Hi! Welcome to Python Programming

Cool Tip: How to remove multiple characters from a string in Python!

Using str.strip() for stripping quotes from both ends of a string

strip() method takes chars as input and strips the character from both ends of the string. The strip method removes the quotes from the ends and leaves quotes that are in the middle of the string.

To strip quotes from a string in Python using strip():

  1. Call the str.strip() on a string and pass a ‘”‘ to search for in the string.
  2. The strip() returns a copy of the string where it removes quotes from both ends of the string.
my_string = '"Hi!" "Welcome to Python Programming"'

str2 = my_string.strip('"')
print(str2)

The output of the above Python program after stripping quotes from a string is:

Hi!" "Welcome to Python Programming

Cool Tip: How to remove line breaks in Python!

Conclusion

I hope the above article on how to remove quotes from a string in Python using str.replace() is helpful to you.

You can find more topics about the Python tutorials on the DataVisualizr Home page.

Leave a Comment