首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果字符串中发生了特定的子字符串,如何使用python返回子字符串?

问如果字符串中发生了特定的子字符串,如何使用python返回子字符串?
EN

Stack Overflow用户
提问于 2022-10-31 07:46:27
回答 1查看 38关注 0票数 3

我试图使用python返回或打印在搜索关键字之前出现的特定子字符串。

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

代码语言:javascript
复制
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"

如果搜索关键字是apple,则应该打印0 (即id)。

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

如果搜索关键字为fox,则应打印3和4 (即id)。

我期待的是关键字的id,如本例所示。在我的示例中,所有可搜索的关键字都与id相关联,如示例字符串中所示。

EN

回答 1

Stack Overflow用户

发布于 2022-10-31 08:04:16

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

代码语言:javascript
复制
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'))

输出:

代码语言:javascript
复制
[3, 4]

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

代码语言:javascript
复制
return re.findall(pattern, string)
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74260133

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档