如何在python中提取选定字符串之间的字符串

如何在python中提取选定字符串之间的字符串,python,Python,如果我有一个字符串,比如: str = 'Hello, <code>This is the string i want to extract</code>' 那么如何提取介于和之间的字符串,在上述情况下,提取字符串为: 'This is the string i want to extract' 我想在django筛选器中使用此字符串。使用解析器,如BeautifulSoup: >>> from bs4 import BeautifulSoup as

如果我有一个字符串,比如:

str = 'Hello, <code>This is the string i want to extract</code>'
那么如何提取介于
之间的字符串,在上述情况下,提取字符串为:

'This is the string i want to extract'

我想在django筛选器中使用此字符串。

使用解析器,如
BeautifulSoup

>>> from bs4 import BeautifulSoup as BS
>>> text = 'Hello, <code>This is the string i want to extract</code>'
>>> soup = BS(text)
>>> print soup.code.text
This is the string i want to extract
或者,如果只有一行,则可以使用正则表达式:

>>> import re
>>> re.search(r'<code>(.*?)</code>', text).group(1)
'This is the string i want to extract'

顺便说一下,请不要给字符串命名
str
。它将覆盖内置类型。

如果还需要“Hello”,请尝试此操作


欢迎来到堆栈溢出!看起来你想让我们为你写些代码。虽然许多用户愿意为陷入困境的程序员编写代码,但他们通常只在海报已经试图自己解决问题时才提供帮助。演示这项工作的一个好方法是,包括您迄今为止编写的代码、示例输入(如果有)、预期输出和实际获得的输出(控制台输出、堆栈跟踪、编译器错误——任何适用的)。你提供的细节越多,你可能得到的答案就越多。@MartijnPieters同意。我没有给出任何尝试性的解决方案,因为我不知道该怎么做,因为我是python学习者,我还没有学习python正则表达式,也不知道BeautifulSoup。在我的尝试中,我只是应用了“for”和“if”循环,这与真实答案或我真正想做的事情并不接近。@alko:我的是基于我在这里找到的文本。我现在能找到的最早的参考资料是去年11月7日,我再也找不到基于我的原始文本了。@alko:请注意,“欢迎使用堆栈溢出!”部分是由我使用的脚本自动添加的,适用于网站上的新用户。回答得好,Haidro!:regex和BS均为D+1。谢谢@Haidro。帮了大忙。@NishantBhakta没问题:)
from bs4 import BeautifulSoup
import re
sentence = 'Hello, <code>This is the string i want to extract</code>'   
print re.sub('<[^>]*>', '',  sentence)

Hello, This is the string i want to extract