获取字符串匹配中的单词索引

2024-06-28 16:03:28 发布

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

我有两条线。你知道吗

str = "This is an example sentence, it is for demonstration only"

k = "example sentence"#k可能包含一个或多个单词

我想在str中找到k,但我需要单词索引。 我分裂了str

splitted_str = str.split()

print(splitted_str)
['This', 'is', 'an', 'example', 'sentence,', 'it', 'is', 'for', 'demonstration', 'only']

如果我匹配splitted_str中的k,那么函数应该给我example的索引3和sentence的索引4。你知道吗

re.search().start()它只给出字符串起始索引。你知道吗

请建议。你知道吗

提前谢谢。你知道吗


Tags: anonlyforisexampleitthis单词
1条回答
网友
1楼 · 发布于 2024-06-28 16:03:28

试着把你短语上的句子分开,然后数一数前面的单词。你知道吗

>>> str = "This is an example sentence, it is for demonstration only"
>>>
>>> k = "example sentence"
>>> str.split(k)
['This is an ', ', it is for demonstration only']
>>> str.split(k)[0].split()
['This', 'is', 'an']
>>> len(str.split(k)[0].split())
3
>>>

相关问题 更多 >