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

如何使用Python列表中的整数作为索引对字符串进行切片

问题原因

你的代码存在两个核心错误:

  • 循环遍历的是words的元素值(0、4、10、15),不是列表的下标索引,直接用words[i]取值会出现下标越界问题
  • 你错误地对words列表做了切片,没有取列表中连续两个数值作为字符串的切片起止参数

修复方案

写法1:遍历索引(易理解)

s = 'heliCopterRotorMotor'
words = [0,4,10,15]
spisok = []
# 遍历到倒数第二个元素即可,每次取下一个元素作为切片终点
for i in range(len(words) - 1):
    start = words[i]
    end = words[i+1]
    slice_res = s[start:end]
    spisok.append(slice_res)
    print(slice_res)

运行输出:

heli
Copter
Rotor

如果需要把字符串末尾剩下的Motor也切出来,只需要在words列表末尾追加len(s)即可。

写法2:zip配对(更简洁)

s = 'heliCopterRotorMotor'
words = [0,4,10,15]
for start, end in zip(words, words[1:]):
    print(s[start:end])

运行效果和上述写法完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 01:57:03