如果字符串中出现特定子字符串,如何使用 python 返回子字符串?

Lal*_*s M 3 python

我正在尝试使用 python 返回或打印一个非常长的字符串中搜索关键字之前出现的特定子字符串。

例如,如果我的字符串如下

string = "id:0, an apple a day keeps the doctor away, id=1, oranges are orange not red, id=3, fox jumps over the dog, id=4, fox ate grapes"
Run Code Online (Sandbox Code Playgroud)

如果搜索关键字是 apple 那么0(即 id)应该被打印

如果搜索关键字是橙色,1则应打印该关键字(即 id)

如果搜索关键字是fox,那么应该打印3 and 4(即id)

我期待示例中给出的关键字id 。就我而言,所有可搜索关键字都与示例字符串中的id相关联。

bn_*_*_ln 5

您可以使用以下正则表达式返回索引和关键字匹配。

import re

def find_id(string, word):
    pattern = r'id[:=](\d+),[\w\s]+' + word
    return list(map(int, re.findall(pattern, string)))

string = "id:0, an apple a day keeps the doctor away, id=1, oranges are orange not red, id=3, fox jumps over the dog, id=4, fox ate grapes"

print(find_id(string, 'fox'))
Run Code Online (Sandbox Code Playgroud)

输出:

[3, 4]
Run Code Online (Sandbox Code Playgroud)

我已经返回了ints 但如果这不是必需的,那么您可以['3', '4']通过将返回行替换为;将索引作为字符串返回

return re.findall(pattern, string)
Run Code Online (Sandbox Code Playgroud)