如何在另一个字符串出现后返回子字符串?

2024-09-28 05:35:56 发布

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

我有一个很长的字符串,我试图在它发生之后返回一个字符串 另一根绳子。例如,我首先在字符串中查找字符串“zombiesattack”,我 然后查找字符串“title”出现的第一个位置,并希望将“title”和“/title”之间的文本保存到另一个名为“titleOfVideo”的变量中。我做这个有点困难。有什么建议吗?在

存储在名为data的变量中的字符串

data= <updated>2012-10-10T19:20:55.000Z</updated>
<abc>zombiesattack</abc>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://gdata.youtube.com/schemas/2007#video" />
<category scheme="http://gdata.youtube.com/schemas/2007/categories.cat" term="Sports" label="Sports" />
<title>NY Yankees: 6 Essential Pieces of Postseason Memorabilia</title>

我想把“纽约扬基队:6个季后赛重要纪念品”保存到变量“标题视频”。在

^{pr2}$

当我尝试这个并打印视频标题时,我得到了一堆返回线。在


Tags: 字符串comhttpdatatitleyoutubeschemasscheme
2条回答

请改用XML解析器,例如ElementTree:

from xml.etree import ElementTree
# you need a valid xml string
data = '<root>' + data + '</root>'
etree = ElementTree.fromstring(data)
if etree.findtext('abd') == 'zombiesattack':
    titleOfVideo = etree.findtext('title')

对于这个特殊的例子:

starting_point = data.find('zombiesattack')
new_string = data[starting_point:]
title_start = new_string.find('<title>')
title_end = new_string.find('</title>')
titleOfVideo = new_string[title_start + len('<title>'):title_end]

相关问题 更多 >

    热门问题