Python Forum
Escape Single quotation between each content tag - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Escape Single quotation between each content tag (/thread-33521.html)



Escape Single quotation between each content tag - usman - May-01-2021

Hello All,

I am trying to escape a Quotation between content tag of this string

"[[('name', 'productname_0'), ('type', 'html'),('content', 'O'Cornor')],[('name', 'productname_1'), ('type', 'html'), ('content', 'Philp's')]]"


Previously I had this string
"[[('name', 'productname_0'), ('type', 'html'),('content', 'A Cool Shirt')],[('name', 'productname_1'), ('type', 'html'), ('content', 'A Cool Shirt')]]" 
Its working fine. But When I added Single Quotation inside quotation 'O'Cornor'
Example : ('content', 'O'Cornor')

Its giving me syntax error issue. How Can I escape Single Quotation between content value only

*content is Key
* O'Cornor is value between single quotation


RE: Escape Single quotation between each content tag - menator01 - May-01-2021

escape with \ or use double quotes.
print('This is Tom\'s car')
#or
print("This is Tom's car")
Output:
This is Tom's car This is Tom's car



RE: Escape Single quotation between each content tag - usman - May-02-2021

(May-01-2021, 09:35 PM)menator01 Wrote: escape with \ or use double quotes.
print('This is Tom\'s car')
#or
print("This is Tom's car")
Output:
This is Tom's car This is Tom's car

Thank you. Is there anyway to only escape only what inside ('content', 'Philp's') content tag. There could multiple content tags in my string.


RE: Escape Single quotation between each content tag - snippsat - May-02-2021

(May-02-2021, 08:28 AM)usman Wrote: Is there anyway to only escape only what inside ('content', 'Philp's') content tag. There could multiple content tags in my string.
Can use a regex,so this Lookahead and Lookbehind ' to see that's there a word character on each end.
import re
import json

s = "[[('name', 'productname_0'), ('type', 'html'),('content', 'O'Cornor')],[('name', 'productname_1'), ('type', 'html'), ('content', 'Philp's')]]"
result =  re.sub(r"(?<=\w)\'(?=\w)", r"\\'", s)
print(result)
d = json.dumps(result)
print(json.loads(d))
Output:
[[('name', 'productname_0'), ('type', 'html'),('content', 'O\'Cornor')],[('name', 'productname_1'), ('type', 'html'), ('content', 'Philp\'s')]] [[('name', 'productname_0'), ('type', 'html'),('content', 'O\'Cornor')],[('name', 'productname_1'), ('type', 'html'), ('content', 'Philp\'s')]]