سؤال

Why does the following result in an error?

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

I'd like to call sub on strings that contain forward slashes, not sure why it results in this error. How can it be fixed so that I can pass strings with '/' characters in them to sub()?

thanks.

هل كانت مفيدة؟

المحلول

Because re.sub calls the repl parameter with an instance of re.match.

I think you want to use:

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

However, a simpler way of doing this might be to use the safe argument to urllib.quote:

urllib.quote("A/B", safe="/.: ^*$@!+_?-")
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top