python - 如何在列表中搜索或查找特定子字符串

标签 python list

value = ["python:guru-age20",
         "is_it_possible_time100:goodTime99",
         "hmm_hope_no_onecanansswer"]

如何从该字符串列表中获取特定字符串?我需要从 li[1] 字符串中找到 goodTime99 及其确切位置

if value.find("goodTime99") != -1: 我知道如果我给出整个字符串 is_it_possible_time100:goodTime99 就会起作用。

否则如何通过搜索 goodTime99 而不是搜索 is_it_possible_time100:goodTime99 来精确定位? value.index("goodTime99") 出现错误。

我不是在寻找整个字符串来搜索,value.index("is_it_possible_time100:goodTime99") 很好,但我不想要这个。无论如何要这样做吗?

最佳答案

如果您只想检查列表中的任何字符串中是否存在“goodTime99”,您可以尝试:

value = ["python:guru-age20", "is_it_possible_time100:goodTime99","hmm_hope_no_onecanansswer"]
if any("goodTime99" in s for s in value):
    # found it

如果您需要确切的位置:

>>> next((i for i, s in enumerate(value) if "goodTime991" in s), -1)
1

或者:

def find_first_substring(lst, substring):
    return next((i for i, s in enumerate(lst) if substring in s), -1)

>>> find_first_substring(value, "goodTime99")
1

关于python - 如何在列表中搜索或查找特定子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12970204/

相关文章:

Python Numpy - 矩阵内存错误和限制

python将多行中的单词提取到1个列表中

python - 从字符串列表中查找最常见的单词

c# - 检查列表中的键/值对

java - 在 java 特殊用例的迭代过程中添加项目

python - 另一个转换 hh :mm:ss to seconds

python - 如何使用 PyAIML 设置聊天机器人的主人名称?

python - 如何摆脱 Flask/mongoengine 的 json 响应中的数据类型

python - 将相同的变量添加到元组列表中

r - 将命名列表转换为仅包含值的向量