如何在第一个索引号之前打印文本?

2024-05-23 17:59:51 发布

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

这是我的代码:

>>> 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之前)的所有文本?你知道吗


Tags: 代码text文本reansearchisexample
1条回答
网友
1楼 · 发布于 2024-05-23 17:59:51

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

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

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

相关问题 更多 >