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

Python中如何替换字符串指定文本?代码输出未达预期需求

解决字符串指定位置添加内容的问题

你当前的代码用replace("-1", "_s", 1)是把字符串里的-1整个替换成了_s,所以才会得到Image_s.jpg。要实现保留-1并在后面添加_s的效果,只需要修改替换的目标内容即可:

修改后的代码:

Image = "/home/user/Picture/Image-1.jpg"
Image2 = Image.replace("-1", "-1_s", 1)
print(Image)
print(Image2)

运行输出:

/home/user/Picture/Image-1.jpg
/home/user/Picture/Image-1_s.jpg

如果不想用replace,也可以通过分割字符串再拼接的方式实现:

Image = "/home/user/Picture/Image-1.jpg"
prefix, suffix = Image.split("-1", 1)
Image2 = f"{prefix}-1_s{suffix}"
print(Image2)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 08:50:27