Python:从字符串中删除 URL,URL 包含反斜杠

Python: Remove URL from string, URL containing backslashes

我需要从字符串列表中删除 URL(仅替换为 http),但某些 URL 中包含反斜杠 (\)。上网查了一下,发现\是Python中的转义符。我发现的 Whosebug 答案对我的任务没有帮助。

s = 'Future Of Education http://twitter.com/A6y2s9Hyys\xa0 Some right, some wrong.'
re.sub(r'http\S+', 'http', s)

我得到的结果是 Future Of Education http\xa0 Some right, some wrong. 而不是我想要的结果 Future Of Education http Some right, some wrong. 所以我认为问题是我找不到一种方法来处理字符串中的反斜杠?

有什么建议吗?谢谢!

\xa0 不是 URL 的一部分,它是 unicode 不间断的 space 字符。您可以将正则表达式更新为 http://\S+ 以删除 url:

末尾的 \xa0
s = 'Future Of Education http://twitter.com/A6y2s9Hyys\xa0 Some right, some wrong.'
print(re.sub(r'http://\S+', 'http', s))

输出:

Future Of Education http  Some right, some wrong.

感谢@ctwheels 更新正则表达式。