Replace Single Quote With Double Quote in a String Python

Replace single quote with double quote in a string python

The outer quotes in a string literal are not part of the string, they indicate that you have a string object.

By going from 'TEST' to "'TEST'" you are not replacing anything. You are adding two single quotes to a string of length 4!

>>> t1 = 'TEST'
>>> t2 = "'TEST'"
>>> len(t1)
4
>>> len(t2)
6

That being said, you can use repr to get the second string as desired.

>>> repr(t1)
"'TEST'"

This is a quick hack (see comments), it's more robust and explicit to use

"'{}'".format(t1)

Replace single and double quote in string

For your exemple to work correctly you have to escape the \ character also:

lote.descripcion.replace("'", '\\\'')
lote.lote.replace("'", "\\'")

But you can also check about MarkupSafe which will do it for you. This library is specially done so you can safely insert strings in you html code.

Edit: @RobinZigmond is correct

Replace double quotes with single quotes between pairs of square brackets

You can omit the capture group from the pattern as you are replacing on the whole match.

The pattern \[(\".*?\",?)*\] can also match a , at the end, and uses a non greedy match between the double quotes.

What you might do is use a negated character class [^"]* instead to match all between the double quotes, and optionally repeat a non capture group(?:\s*,\s*"[^"]*")* with a leading comma to not allow a comma at the end.

re.sub can use a lambda where you might also do the replacement of the double quotes.

import re

a = """abcda"sd"asd["first", "last", "middle", "dob", "gender"]"""
a = re.sub(r'\["[^"]*"(?:\s*,\s*"[^"]*")*', lambda m: m.group().replace('"', "'"), a)
print(a)

Output

abcda"sd"asd['first', 'last', 'middle', 'dob', 'gender']


Related Topics



Leave a reply



Submit