Python Replace Single Quotes with Double Quotes

You can replace single quotes with double quotes in a Python string using the replace() method. Here’s a simple example:

original_string = "This is a 'sample' string with 'single quotes'."

# Replace single quotes with double quotes
modified_string = original_string.replace("'", '"')

print("Original string:", original_string)
print("Modified string:", modified_string)

This will output:

Original string: This is a 'sample' string with 'single quotes'.
Modified string: This is a "sample" string with "single quotes".

In this example, replace(“‘”, ‘”‘) replaces all occurrences of single quotes (‘) with double quotes (“).

Example 1: Python String Replace Single Quotes with Double Quotes

main.py

myString = "Empowering 'Progress' through Tech"

# python string replace single quotes with double
newString = myString.replace("'", '"')

print(newString)

Result:

Empowering "Progress" through Tech

Example 2: Python String Replace Double Quotes with Single Quotes

main.py

myString = 'Empowering "Progress" through Tech'

# python string replace double quotes with single
newString = myString.replace('"', "'")

print(newString)

Result:

Empowering 'Progress' through Tech

Example 3: Python List Replace Double Quotes with Single Quotes

main.py

import json

allitems = ["Empowering", "Progress", "through", "Tech"]

# python list replace double quotes with single
final_output = [item.replace("'", '"') for item in allitems]

print(final_output);

Result:

['Empowering', 'Progress', 'through', 'Tech']

Example 4: Python List Replace Single Quotes with Double Quotes

main.py

import json

allitems = ['Empowering', 'Progress', 'through', 'Tech']

# python list replace single quotes with double
final_output = json.dumps(allitems)

print(final_output);

Result

["Empowering", "Progress", "through", "Tech"]

Leave a Comment