urllib和正则表达式替换错误

时间:2011-12-03 23:22:39

标签: python regex escaping urllib python-2.7

为什么以下导致错误?

import re
from urllib import quote as q
s = re.compile(r'[^a-zA-Z0-9.: ^*$@!+_?-]')
s.sub(q, "A/B")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/python/python-2.7.1/lib/python2.7/urllib.py", line 1236, in quote
    if not s.rstrip(safe):
AttributeError: rstrip

我想在包含正斜杠的字符串上调用sub,不确定为什么会导致此错误。如何修复它以便我可以将带有'/'字符的字符串传递给sub()?

感谢。

1 个答案:

答案 0 :(得分:2)

由于re.sub使用repl的实例调用re.match参数。

我想你想用:

s.sub(lambda m: q(m.group()), "A/B")

但是,更简单的方法是使用safe的{​​{1}}参数:

urllib.quote
相关问题