首页 > 解决方案 > Python string.replace() 不替换某些字符

问题描述

def replace_at_index(string, index):
    print (string.replace(string[index], "-", 1))

这是我当前用给定索引替换字符的代码。

不知道它为什么这样做。我想要的结果是它替换给定的索引,在“Housee”索引5的情况下将是“House-”

标签: python

解决方案


这是一个黑客但有效:

def replace_at_index(string, index):
   ls = list(string)
   ls[index] = "-"
   s = "".join(ls)
   print(s)

推荐阅读