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

如何替换字符串中指定位置的切片?已知起止位置

已知切片位置替换字符串指定内容

假设原字符串为:Long long ago, there lived a king.

已知第二个"long"的起始索引为5,结束索引为9(字符串索引从0开始,切片遵循左闭右开规则),要将其替换为"ABCD",可以通过字符串切片拼接的方式实现,以Python为例:

original_str = "Long long ago, there lived a king."
start_idx = 5
end_idx = 9
replace_str = "ABCD"

new_str = original_str[:start_idx] + replace_str + original_str[end_idx:]
print(new_str)

运行后输出结果为:Long ABCD ago, there lived a king.

核心逻辑

  • 用original_str[:start_idx]截取原字符串中目标切片之前的部分
  • 拼接上要替换的内容replace_str
  • 再拼接原字符串中目标切片之后的部分original_str[end_idx:]

这种逻辑适用于大多数支持字符串切片与拼接的编程语言,操作思路一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 23:40:53