python - Python string.replace() 不替换某些字符
问题描述
def replace_at_index(string, index):
print (string.replace(string[index], "-", 1))
这是我当前用给定索引替换字符的代码。
- 索引为 4 的字符串“House”产生“Hous-”
- 索引为 5 的字符串“Housee”产生“House-e”
- 索引为 6 的字符串“Houseed”产生“Housee-”
- 索引为 5 的字符串“Houseed”产生“Hous-ed”
不知道它为什么这样做。我想要的结果是它替换给定的索引,在“Housee”索引5的情况下将是“House-”
解决方案
这是一个黑客但有效:
def replace_at_index(string, index):
ls = list(string)
ls[index] = "-"
s = "".join(ls)
print(s)
推荐阅读
- visual-studio - 如何从 Visual Studio 部署到 Azure
- javascript - 用户在输入标签中写入后,如何立即将用户英语数字更改为波斯语/阿拉伯语?
- html - 如何在 cookie __RequestVerificationToken_Lw__ 上设置属性 samesite 的值
- vue.js - 检测到重复键(无 v-for)
- cmake - CMake:Fortran 模块和编译顺序
- amazon-s3 - 如果我事先不知道查询,我应该如何为 AWS Athena (Presto) 分区数据?
- html - 订阅本地图书馆的服务
- javascript - 如何使用 XmlHttpRequest 发送 FormData 并映射到 viewmodel 属性
- javascript - 在 javascript 中设置暂停/恢复定时器
- javascript - 具有更改图像功能的 if/else 语句不适用于多个图像