<p>这些似乎是<a href="http://docs.python.org/library/re.html" rel="nofollow">regular expressions</a>。正则表达式允许您以一种相当强大和复杂的方式搜索字符串中的模式。不过,它们可能有点神秘。这些似乎是某种原始喋喋不休的基础。你知道吗</p>
<pre><code>>>> import re
>>> regex, phrases = (r'why (.*) i (.*)\?',
... ( "You %s %s?",
... "Perhaps you only think you %s %s"))
>>> phrase1, phrase2 = phrases
>>> groups = re.search(regex, 'why am i dumb?')
>>> phrase1 % (groups.group(1), groups.group(2))
'You am dumb?'
>>> phrase2 % (groups.group(1), groups.group(2))
'Perhaps you only think you am dumb'
</code></pre>
<p>啊,也许你特别想知道<code>r'blahblah'</code>是什么意思。正如其他人所解释的,<code>r</code>只是使它成为一个原始字符串,Python没有对它进行某些处理,这使得REs更易于阅读。你知道吗</p>
<hr/>
<p>这里有一些更接近我的初衷是为了这些字符串。他们似乎没有使用标准的Python组替换语法,所以我假设他们必须使用一个定制的替换函数,这个函数可能足够复杂,可以处理动词形式的转换!您可以看到基本思想<a href="http://docs.python.org/library/re.html#re.sub" rel="nofollow">here</a>。你知道吗</p>
<pre><code>>>> import re
>>> regex, phrases = (r'why (.*) i (.*)\?',
... ( r'You \g<1> \g<2>?',
... r'Perhaps you only think you \g<1> \g<2>.'))
>>> phrase1, phrase2 = phrases
>>> re.sub(regex, phrase1, 'why am i dumb?')
'You am dumb?'
>>> re.sub(regex, phrase2, 'why am i dumb?')
'Perhaps you only think you am dumb.'
</code></pre>