Quotes in strings with python
December 15, 2005
AK has a rant about python and why it’s not his favourite language. He writes:
1. # replace *text* by '''text'''. 2. p = re.compile('*([^*]+)*',re.MULTILINE) 3. text = p.sub(r"""'''\1'''""",text)So many quotes, just awful, and so absolutely un-intuitive.
First of all your regex will not work when you don’t escape the asterisks (the blog’s markup has eaten the backslashes?) and maybe I am missing something here, but why should we need multiline (raw) strings for the substitution? It should work with single double quotes.
>>> import re
>>> p = re.compile ('\*([^*]+)\*', re.MULTILINE)
>>> text = "convert the *markup*"
>>> print p.sub(r"'''\1'''", text)
convert the '''markup'''
Is there a better way to enter your string?
>>> s = "'" * 3 >>> print r"%s\1%s" % (s,s) '''\1'''
IMHO not much better … but the following is an interesting approach (but not really suited for this simple problem):
>>> from string import Template
>>> s = Template('$threesinglequotes\\1$threesinglequotes')
>>> singlequote = "'"
>>> s.substitute(threesinglequotes=singlequote*3)
"'''\\1'''"
>>> p.sub(s.substitute(threesinglequotes=singlequote*3), text)
"convert the '''markup'''"
Hmm, overhead but readable, I’d prefer the simple string above.
BTW, which language supports better syntax to define the string “”’\1”’”?
Posted in



