python - 如何从索引数组中替换字符串中的字符?
问题描述
假设我有一个空数组:
ws = []
和字符串:
text = "cmon lets go"
我将检查空格并在 ws 数组中存储空格索引,因此之后我将拥有:
ws = [4, 9]
然后我会有一些其他的字符串:
new_string = "cmonzletszgo"
假设所有空格都用字母 z 切换(没关系)。现在我想遍历 new_string 并用空格替换数组 ws 中索引中的字符所以我想得到
new_string = "cmon lets go"
解决方案
由于您有要替换的索引,因此您可能想尝试迭代ws
而不是new_string
:
for i in ws:
new_string = new_string[:i] + ' ' + new_string[i + 1:]
这将在new_string
中指定的索引处将字符替换为空格ws
,而不管当前可能存在什么字符。
推荐阅读
- python - 使用 Pandas 将 SAS 转换为 Python
- php - Laravel 推送器未在 Localhost 中进行身份验证,但在 Development Server 中进行了身份验证
- css - 添加具有背景 CSS 属性的视频
- sql - SYS_REFCURSOR 作为函数中的输出参数
- excel - Excel 列表中的部分搜索列并填充相邻单元格
- godot - Godot GDScript“参数太多”错误
- python - opencv - 如何检查轮廓位置
- google-identity - 谷歌身份服务实现手动和自动退出功能
- sql - 达到值后限制查询结果
- android - recyclerView 的项目滚动到 recyclerView 之外