用最后一个ch的扩展提取子串

2024-10-06 13:22:03 发布

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

我的意图是提取子字符串并将它们扩展到大字符串中的下两个单词。下面是字符串,一个索引列表和输出,以提供清晰的说明。你知道吗

示例:

>>> _string='the old school teacher is having a nice time at school'
>>> index_list=[[0,8],[23,35]]
>>> [_string[x[0]:x[-1]] for x in index_list]
Output:>>> ['the old s', 'is having a n']

我的目标不是扩展子字符串来覆盖接下来的两个单词。subs字符串的最后一个字符应该扩展到teacher和time。你知道吗

期望输出:

['the old school teacher', 'is having a nice time']

如果你需要更多的解释,请告诉我。你知道吗

有什么建议吗?你知道吗


Tags: the字符串列表stringindextimeis单词
1条回答
网友
1楼 · 发布于 2024-10-06 13:22:03

这是一个很简单的方法。。。你知道吗

>>> def tiger(inval, start, end):
...     base = list(inval[start: end])
...     spaces = 0
...     while spaces < 2 and end < len(inval):
...         char = inval[end]
...         if char == " ":
...             spaces += 1
...         base.append(char)
...         end += 1
...     return "".join(base).strip()
...
>>> tiger(_string, 0, 8)
'the old school teacher'
>>> tiger(_string, 23, 35)
'is having a ice time'
>>> tiger(_string, 45, 85)
'at school'

这假设您总是假设单词在空格(而不是标点符号)上被拆分,尽管一个简单的正则表达式或字符集可以解决这个问题。你知道吗

相关问题 更多 >