Python urllib和正则表达式替换错误

Python urllib和正则表达式替换错误,python,regex,escaping,urllib,python-2.7,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

为什么以下情况会导致错误

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
重新导入
从urllib导入报价为q
s=重新编译(r'[^a-zA-Z0-9:^*$@!+?-]))
s、 分包(q,“A/B”)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“/python/python-2.7.1/lib/python2.7/urllib.py”,第1236行,在引号中
如果不是s.rstrip(安全):
属性错误:rstrip
我想对包含正斜杠的字符串调用sub,但不确定为什么会导致此错误。如何修复它,以便我可以将带有“/”字符的字符串传递给sub()


谢谢。

因为
re.sub
使用
re.match
的实例调用
repl
参数

我想你应该使用:

s.sub(lambda m: q(m.group()), "A/B")
但是,一种更简单的方法可能是使用
safe
参数来
urllib.quote

urllib.quote("A/B", safe="/.: ^*$@!+_?-")