如何删除python字符串中包含子字符串的单词?

2024-07-02 11:07:38 发布

您现在位置:Python中文网/ 问答频道 /正文

当我在使用Twitter API时,我得到了几个包含链接的字符串(tweets),这就是它用'http://'来乞讨的子字符串。在

我怎样才能去掉这些链接,就这样,我想把整个单词都去掉。在

假设我有:

'Mi grupo favorito de CRIMINALISTICA. Ultima clase de cuatrimestre http://t.co/Ad2oWDNd4u'

我想得到:

^{pr2}$

这样的子串可以出现在字符串的任何地方


Tags: 字符串apihttp链接detwitter单词tweets
2条回答

你可以这样做:

s[:s.index('http://')-1]

如果它不总是出现在末尾,可以执行以下操作:

^{pr2}$

可以使用re.sub()将所有链接替换为空字符串:

>>> import re
>>> pattern = re.compile('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+')
>>> s = 'Mi grupo favorito de CRIMINALISTICA. Ultima clase de cuatrimestre http://t.co/Ad2oWDNd4u'
>>> pattern.sub('', s)
'Mi grupo favorito de CRIMINALISTICA. Ultima clase de cuatrimestre '

它将替换字符串中任何位置的所有链接:

^{pr2}$

正则表达式取自此线程:

相关问题 更多 >