[Tutor] quoting and escaping
Jon Crump
jjcrump at myuw.net
Wed Jan 14 00:09:26 CET 2009
All,
Something I don't understand (so what else is new?) about quoting and
escaping:
>>> s = """ "some" \"thing\" """
>>> s
' "some" "thing" '
I've got strings like this:
s = """[{"title" : "Egton, Yorkshire", "start" : new Date(1201,1,4),
"description" : "Hardy's long name: Egton, Yorkshire. <br> "},
{"title" : "Guilsborough, Yorkshire", "start" : new Date(1201,1,5),
"description" : "Hardy's long name: Guilsborough, Yorkshire. <br>
<img src=\"document.png\" style=\"cursor: pointer\"
onclick=\"SimileAjax.WindowManager.cancelPopups();show_next('tab3');pager('006');
return false\"/>pg.006: 1201-02-05 to 1202-03-07"}]"""
Thanks to your good help, I can re.sub() to translate the new Date()
objects into "datetime.date()" instances, thus:
[{"title" : "Egton, Yorkshire", "start" : "date(1201, 02, 04)",
"description" : "Hardy's long name: Egton, Yorkshire. <br> "},
{"title" : "Guilsborough, Yorkshire", "start" : "date(1201, 02, 05)",
"description" : "Hardy's long name: Guilsborough, Yorkshire. <br>
<img src="document.png" style="cursor: pointer"
onclick="SimileAjax.WindowManager.cancelPopups();show_next('tab3');pager('006');
return false"/>pg.006: 1201-02-05 to 1202-03-07"}]
with the quotation marks, eval() evaluates these date() instances
correctly; however, python treats " and \" as if they were identical so I
wind up with bad syntax: multiple doublequoted strings in a dictionary
value. How can I identify \" in a regex so that I can replace it with
something that eval() won't choke on?
This is pretty confusing to me, so I've tried to provide clarification
below:
>>> a = """{"aKey" : "aValue"}"""
>>> eval(a)
{'aKey': 'aValue'}
## so far so good, but then:
>>> b = """{"aKey" : "a value with \"literal quotes\" in it"}"""
>>> eval(b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
{"aKey" : "a value with "literal quotes" in it"}
^
SyntaxError: invalid syntax
More information about the Tutor
mailing list