In this tutorial, we will look at how to replace single quotes in a Python string with double quotes with the help of some examples.
Replace '
with "
inside a string
Let’s see an example to better understand the task at hand. Let’s say you have the string, "This is a 'safe' place"
. After replacing the single quotes with double quotes, the resulting string should be 'This is a "safe" place'
.
How to replace single quotes with double quotes in a string?
You can use the following methods to replace single quotes with double quotes in a Python string.
- Using the string
replace()
function to replace all single quotes with double quotes. - Using a translation table to map every single quote with a double quote.
Let’s now look at both these methods with the help of some examples.
Highlighted programs for you
Flatiron School
Flatiron School
University of Maryland Global Campus
University of Maryland Global Campus
Creighton University
Creighton University
Example 1 – Using the string replace()
function
The built-in string replace()
function used to replace occurrences of a string with another string. To replace single quotes with double quotes, pass a single quote as the first argument and a double quote (using escape sequence) as the second argument.
Let’s look at an example.
# create a string s = "This is a 'safe' place" # display the string print(s) # replace single quotes with double quotes res = s.replace("'", """) # display the result print(res)
Output:
This is a 'safe' place This is a "safe" place
You can see that the single quotes have been replaced by double quotes in the resulting string.
Example 2 – Using the string translate()
function
The string translate()
function is used to apply a translation map on a string. Use the str.maketrans()
function to create a translation map (also called translation table), mapping quotes to double quotes.
Let’s look at an example.
# create a string s = "This is a 'safe' place" # display the string print(s) # replace single quotes with double quotes res = s.translate(str.maketrans({"'": """})) # display the result print(res)
Output:
This is a 'safe' place This is a "safe" place
The single quotes have been replaced by the double quotes in the resulting string.
You might also be interested in –
- Swap the Case of a Python String with the swapcase() method
- Swap Adjacent Characters in a Python String with this Method
- Python String Replace – With Examples
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.