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

如何获取给定字符串中所有空格的索引位置

问题原因

str.index() 方法默认仅从字符串起始位置查找,只返回第一个匹配项的索引,所以无法直接获取后续的空格位置。


解决方法

方法1:列表推导式+enumerate(最推荐,简单高效)

遍历字符串的每个字符和对应索引,筛选出字符为空格的索引即可:

Y = "Hell o World!"
space_indices = [i for i, char in enumerate(Y) if char == " "]
print(space_indices)

输出:

[4, 6]

方法2:循环调用index指定查找起始位置

如果需要沿用index方法,可以每次找到空格后,将下一次查找的起始位置设置为当前空格索引+1,直到找不到空格退出循环:

Y = "Hell o World!"
space_indices = []
start = 0
while True:
    try:
        idx = Y.index(" ", start)
        space_indices.append(idx)
        start = idx + 1
    except ValueError:
        # 无匹配空格时结束循环
        break
print(space_indices)

方法3:正则匹配(适合复杂匹配场景)

如果后续有更复杂的匹配需求,可以用re.finditer迭代所有匹配结果,取每个匹配项的起始索引:

import re
Y = "Hell o World!"
space_indices = [match.start() for match in re.finditer(r' ', Y)]
print(space_indices)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 01:12:01