'Forming dynamically request for xpath, problem with quotes
I have some problems with lxml which does not preserve the original file, for example if I have an xml file which contains:
<column caption='Choix Découpage' name='[Aujourd'Hui Parameter (copy 2)]'>
<alias key='"Frais de Services"' value='Offline Fees' />
</column>
and I take a glance at the key attribute of alias node
from lxml import etree
import sys
tree = etree.parse('test.xml')
root = tree.getroot()
print([node.attrib['key'] for node in root.xpath("//alias")]) # we get ['"Billetterie Ferroviaire"']
value = [node.attrib['key'] for node in root.xpath("//alias")][0]
Now if I want to retrieve all the alias nodes with the attribute '"Billetterie Ferroviaire"' I can do (solution given in another post, thanks again):
root.xpath("//alias[@key='\"Frais de Services\"']")
But imagine that I want to dynamically form the query:
"//alias[@key='\"Frais de Services\"']"
but Python uses simple quote for strings, so I can't write exactly this query. Maybe xpath understand other equivalent form? I am a bit lost if someone could explain me why Python use simple Quote and what can I do to solve such problems (is there always alternative ways when I want to generate a string for an other program to feed it with a good structure). Hope to be clear enough to be helped.
Solution 1:[1]
Simply escape those apostrophes which you don't want Python to interpret as closing the string:
test = 'string which contains \'apostrophes\''
The variable test will contain the following string:
string which contains 'apostrophes'
I'm not sure how to explain why Python is using apostrophes to enclose strings. It's simply a decision made by the language designers. Strings can be enclosed in both apostrophes or double quotes and usually, it's a good idea to use those which don't appear in the string they're enclosing (or there's less of them), so you don't need to escape them:
test = "string with 'apostrophes'"
test = 'string with "double quotes"'
test = 'string with both \'apostrophes\' and "double quotes"'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
