Skip to main content

How to Replace Single Quotes with Double Quotes (and Vice Versa) in Strings and Lists in Python

Handling quotation marks within strings is a common task, especially when preparing data for formats like JSON (which strictly requires double quotes) or when standardizing string representations. Python's string methods provide simple ways to replace single quotes (') with double quotes (") or the other way around.

This guide demonstrates how to perform these replacements within individual strings and for all strings within a list using str.replace() and other techniques.

The Goal: Swapping Quote Types

We want to take a string that might contain single quotes and produce a new string where those single quotes are replaced by double quotes, or perform the reverse operation (double to single). We also want to apply this transformation to all string elements within a list.

Example Data:

string_with_singles = "Item: 'apple', Size: 'L'"
string_with_doubles = '{"name": "Tom", "city": "London"}'
list_with_singles = ["'value1'", "'value2'", "no_quotes"]

Replacing Quotes in a Single String

The str.replace(old, new) method is the most direct and standard way to replace all occurrences of one substring with another.

  • Single (') to Double ("):

    string_with_singles = "Item: 'apple', Size: 'L'"
    print(f"Original: {string_with_singles}")

    # Replace all single quotes with double quotes
    # Note: Use contrasting quotes for the arguments ' and "
    result_double = string_with_singles.replace("'", '"')

    print(f"Replaced: {result_double}")

    Output:

    Original: Item: 'apple', Size: 'L'
    Replaced: Item: "apple", Size: "L"
  • Double (") to Single ('):

    string_with_doubles = '{"name": "Tom", "city": "London"}'
    print(f"Original: {string_with_doubles}")

    # Replace all double quotes with single quotes
    # Note: Use contrasting quotes for the arguments " and '
    result_single = string_with_doubles.replace('"', "'")

    print(f"Replaced: {result_single}")

    Output:

    Original: {"name": "Tom", "city": "London"}
    Replaced: {'name': 'Tom', 'city': 'London'}
note

When defining the old and new arguments in replace(), ensure the surrounding quotes defining those arguments don't conflict with the quotes you are trying to replace. For example, use replace("'", '"') or replace('"', "'").

Alternatively, use triple quotes """ or escape the quotes within the arguments (e.g., replace('\'', '"')), but alternating quote types is usually clearest.

Using str.split() and str.join() (Alternative)

You can split the string by the quote you want to remove and then join the resulting parts using the quote you want to insert. This is generally less direct and less readable than replace().

string_with_singles = "Item: 'apple', Size: 'L'"
print(f"Original: {string_with_singles}")

# 1. Split the string by the single quote
parts = string_with_singles.split("'")
print(f"Parts after split: {parts}")

# 2. Join the parts using a double quote as the separator
result_join = '"'.join(parts)
print(f"Rejoined with double quotes: {result_join}")

Output:

Original: Item: 'apple', Size: 'L'
Parts after split: ['Item: ', 'apple', ', Size: ', 'L', '']
Rejoined with double quotes: Item: "apple", Size: "L"

This works but is more complex than necessary for simple quote replacement.

Replacing Quotes within Strings in a List

Goal: Apply the quote replacement to every string element inside a list.

Iterate through the list and apply the replace() method to each element, collecting the results in a new list.

list_with_singles = ["'value1'", "item:'value2'", "'value3'"]
print(f"Original List: {list_with_singles}")

# Use list comprehension and replace() on each item
list_with_doubles = [item.replace("'", '"') for item in list_with_singles]

print(f"List with doubles: {list_with_doubles}")

# Example: Double to single quotes
list_with_doubles_input = ['"A"', '"B"']
list_with_singles_output = [item.replace('"', "'") for item in list_with_doubles_input]
print(f"List with singles: {list_with_singles_output}")

Output:

Original List: ["'value1'", "item:'value2'", "'value3'"]
List with doubles: ['"value1"', 'item:"value2"', '"value3"']
List with singles: ["'A'", "'B'"]
note

This is the standard Pythonic way to transform elements within a list. It creates a new list with the modified strings.

Using json.dumps() (For list-to-JSON string conversion)

If your goal is specifically to get a JSON string representation of a Python list (where strings must be double-quoted), json.dumps() handles this automatically.

import json # Required import

python_list = ['apple', "banana", 'cherry'] # Regular Python list
print(f"Original Python list: {python_list}")

# Convert the whole list to a JSON formatted string
# json.dumps automatically uses double quotes for strings inside the JSON
json_string_output = json.dumps(python_list)

print(f"JSON string representation: {json_string_output}")
print(f"Type of output: {type(json_string_output)}")

Output:

Original Python list: ['apple', 'banana', 'cherry']
JSON string representation: ["apple", "banana", "cherry"]
Type of output: <class 'str'>
note
  • This creates a single string representing the JSON array, not a Python list of strings with double quotes. To get back the Python list: python_list_again = json.loads(json_string_output)
  • Use json.dumps() when you need to serialize the entire list into a valid JSON string format, not just replace quotes within individual string elements while keeping them in a Python list.

Important Note: String Immutability

Remember that Python strings are immutable. Methods like replace(), split(), and join() do not change the original string. They always return a new string with the modifications.

my_string = "use 'this'"
print(f"Original string ID: {id(my_string)}")

new_string = my_string.replace("'", '"')
print(f"New string ID: {id(new_string)}") # Different ID

print(f"Original string is unchanged: '{my_string}'")
print(f"New string: '{new_string}'")

Output:

Original string ID: 140500755609840
New string ID: 140500753223088
Original string is unchanged: 'use 'this''
New string: 'use "this"'
note

To "update" the original variable, reassign it: my_string = my_string.replace("'", '"')

Conclusion

Replacing single quotes with double quotes (or vice versa) in Python is best handled using the str.replace() method.

  • For single strings: new_string = original_string.replace("'", '"') or original_string.replace('"', "'"). Remember to alternate quotes in the arguments or use escapes.
  • For strings within a list: Use a list comprehension: new_list = [item.replace("'", '"') for item in original_list].
  • If converting a Python list/object to a JSON string, use json.dumps(), which automatically handles double-quoting strings according to the JSON standard.

Choose the method based on whether you're operating on a single string or transforming elements within a list.