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

时间:2012-10-12 02:20:43

标签: python string substring

我有一个很长的字符串,我试图在它发生之后返回一个字符串 另一个字串。例如,我首先在字符串中查找字符串'zombiesattack',I 然后查找名为“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件必备品'保存到变量'titleOfVideo'。

starting_point = data.find('zombiesattack')
new_string = data[starting_point:]
title_point = new_string.find('<title>')
print new_string[:title_point]

titleOfVideo = new_string[title_point:20]

当我尝试这个并打印titleOfVideo时,我得到了一堆返回行。

2 个答案:

答案 0 :(得分:0)

对于这个特例:

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]

答案 1 :(得分:0)

使用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')