0

这是我的代码:

>>> text= """ this is an example Item&nbsp;2 text text <B>Item&nbsp;2. example"""
>>> a=re.search ('(?<=<B>)Item&nbsp;2\.',text)
>>> b = a.span()
>>> print (b)
(45, 57)
>>> 

如何打印第一个索引号(45 之前)之前的所有文本?

4

1 回答 1

2

使用text[:start]

In [76]: import re

In [77]: text = """ this is an example Item&nbsp;2 text text <B>Item&nbsp;2. example"""

In [78]: a = re.search ('(?<=<B>)Item&nbsp;2\.',text)

In [79]: start, end = a.span()

In [80]: text[:start]
Out[80]: ' this is an example Item&nbsp;2 text text <B>'

匹配对象a也知道 ; 的值text。它可以通过其string属性访问:

In [91]: a.string[:start]
Out[91]: ' this is an example Item&nbsp;2 text text <B>'
于 2013-07-28T21:14:49.573 回答