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

Python新手求教:如何在字符串中搜索多个单词及正确使用find方法?

在Python字符串中查找多个单词/同一单词的多次出现

首先你遇到的find返回-1的问题,是因为参数顺序错误:str.find(sub, start, end)要求end必须大于等于start,你传入的21, 0不符合规则,所以直接返回-1。

下面是几种可行的解决方法:

方法1:用find/index循环查找所有出现位置

利用find的start参数,每次找到目标位置后,从该位置的下一个字符开始继续查找,直到返回-1为止:

ex = "welcome to my question. you are welcome to be here"
target = "welcome"
start_pos = 0
while True:
    pos = ex.find(target, start_pos)
    if pos == -1:
        break
    print(f"找到 '{target}' 在位置: {pos}")
    # 移动起始位置,避免重复匹配同一位置
    start_pos = pos + len(target)

index方法用法和find几乎一致,区别是找不到目标时会抛出ValueError而非返回-1。

方法2:用正则表达式匹配多目标/多位置

如果需要查找多个不同单词或者处理更复杂的匹配规则,用re模块的finditer方法更灵活:

import re

ex = "welcome to my question. you are welcome to be here"
# 匹配welcome或you,可按需修改正则规则
pattern = re.compile(r'welcome|you')
for match in pattern.finditer(ex):
    print(f"找到 '{match.group()}' 在位置: {match.start()}")

正则还支持扩展场景,比如用r'\bwelcome\b'匹配独立单词、re.IGNORECASE忽略大小写等。

方法3:统计出现次数(无需位置时)

如果只是想知道某个单词的出现次数,直接用字符串的count方法:

ex = "welcome to my question. you are welcome to be here"
print("welcome出现次数:", ex.count("welcome"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 10:15:14