gpt4 book ai didi

python - urllib 和正则表达式替换错误

转载 作者:行者123 更新时间:2023-12-01 06:05:14 26 4
gpt4 key购买 nike

为什么下面的结果会出错?

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()?

谢谢。

最佳答案

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

我想你想使用:

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

但是,更简单的方法可能是使用 urllib.quotesafe 参数:

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

关于python - urllib 和正则表达式替换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8371858/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com