How to Remove Quotes from Strings in Python
This guide explains how to remove quotation marks (both single and double quotes) from strings in Python. We'll cover removing all quotes, removing only leading and trailing quotes, and applying these operations to lists of strings. We'll use the str.replace(), str.strip(), str.lstrip(), str.rstrip(), and generator expressions.
Removing All Quotes from a String
To remove all occurrences of a quote character (single or double) from a string, use the str.replace() method:
Removing All Double Quotes
my_str = 'tutorial "reference" Com "ABC"'
result = my_str.replace('"', '') # Replace all " with empty string
print(result) # Output: tutorial reference Com ABC
my_str.replace('"', ''): This replaces every double quote (") inmy_strwith an empty string (''), effectively deleting them.
Removing All Single Quotes
my_str = "tutorial 'reference' Com 'ABC'"
result = my_str.replace("'", '') # Replace all ' with empty string
print(result) # Output: tutorial reference Com ABC
my_str.replace("'", ''): This replaces every single quote with an empty string.
Removing all quotes from list of strings
my_list = ['"tutorial"', '"reference"', '"com"']
new_list = [item.replace('"', '') for item in my_list]
print(new_list) # Output: ['tutorial', 'reference', 'com']
- The
replace()method is called for every string item in the list, to replace all quotes.
Removing Leading and Trailing Quotes
Sometimes, you only want to remove quotes that appear at the beginning or end of a string (like when cleaning up data).