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_str
with 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).
Removing Specific Leading/Trailing Quotes
Use str.lstrip()
to remove leading quotes and str.rstrip()
to remove trailing quotes:
my_list = ['"tutorial"', '"reference"', '"com"']
new_list = [item.lstrip('"') for item in my_list]
print(new_list) # Output: ['tutorial"', 'reference"', 'com"']
new_list = [item.rstrip('"') for item in my_list]
print(new_list) # Output: ['"tutorial', '"reference', '"com']
item.lstrip('"')
: Removes leading double quotes.item.rstrip('"')
: Removes trailing double quotes.
Removing Any Leading/Trailing Quotes
Use str.strip()
to remove both leading and trailing quotes (either single or double):
my_list = ['"tutorial"', '"reference"', '"com"']
new_list = [item.strip('"') for item in my_list] # Remove leading/trailing double quotes.
print(new_list) # Output: ['tutorial', 'reference', 'com']
- You can provide a string containing any characters you wish to remove.
Removing Quotes with Generator Expressions
For more complex scenarios, or if you need to remove quotes from within the string (not just at the ends), you can use a generator expression:
my_str = "tutorial 'reference' com 'abc' xyz"
result = ''.join(char for char in my_str if char != "'") # Removes all single quotes
print(result) # Output: tutorial reference com abc xyz
- This iterates over each character in the string and builds a new string excluding the single quotes.
- This way you don't have to worry about handling the edge cases.