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
Best Way to Get the Max Value in a Spark Dataframe Column
What Is the Fastest Way to Stack Numpy Arrays in a Loop
How to Continue a Loop After Catching Exception in Try ... Except
How to Get Maximum Length of Each Column in the Data Frame Using Pandas Python
How to Run Linux Terminal Command in Python in New Terminal
How to Plot Multiple Pandas Columns
How to Find 3 Immediate Words After Keyword Match Using Python
Get the First Item from an Iterable That Matches a Condition
Filenotfounderror: [Errno 2] No Such File or Directory
What Is the Simplest Way to Ssh Using Python
Using Python, How to Access a Shared Folder on Windows Network
How to Remove the Decimal Point in a Pandas Dataframe
How to Use Variables in SQL Statement in Python
Delete Rows Containing Numeric Values in Strings from Pandas Dataframe
How to Convert Data from Txt Files to Excel Files Using Python
How to Read a Specific Line from a Text File in Python