You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python列表中查找包含指定字符的字符串的索引?

解决方案

直接用enumerate()遍历列表,同时拿到索引和对应的字符串,判断字符串里是否包含目标字符就行:

s = "Hello StackOverflow!"
lst = s.split(" ")  # ["Hello", "StackOverflow!"]

# 找包含'!'的字符串索引
target = '!'
for index, string in enumerate(lst):
    if target in string:
        print(index)  # 输出1
        break

要是需要复用逻辑,封装成函数更方便:

def get_index_containing_char(str_list, char):
    for idx, s in enumerate(str_list):
        if char in s:
            return idx
    return -1  # 没找到时返回-1

# 调用示例
result = get_index_containing_char(lst, '!')
print(result)  # 1

补充说明

你之前用lst.find('!')不行,是因为列表的find()方法只能查找完整匹配的元素,没法深入检查元素内部的字符,所以必须逐个遍历列表里的字符串,判断字符是否存在其中。

内容的提问来源于stack exchange,提问作者Coder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 00:52:32