使用字符串索引替换字符串中的特定字符

2024-10-02 00:42:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试过使用.replace(),但当我使用索引定义被替换的字符时,它会替换所有与被索引字符相同的字符,如下所示:

string = "cool"
print(string.replace(string[1], "u"))

如果返回:

"cuul"

但我只想替换字符串[1]的索引所对应的特定字符,例如,我希望它可以这样工作:

string = "cool"
print(substitute(string[1],"u")

以便打印:

"cuol"

Tags: 字符串string定义字符replaceprintcoolsubstitute
3条回答

您试图做的是搜索string[1],它是o,并将o的所有实例替换为u

string = "cool"
print(string.replace(string[1], "u"))
# cuul

问题是字符串对象是immutable,因此您只需创建一个新字符串,其中包含所需索引处的值

index = 1
char = 'u'

print(string[:index] + char + string[index+1:])
#cuol
def substitute(string,index,char):
    strlist = list(string)
    strlist[index] = char
    return ''.join(strlist)

这应该起作用:

stirng1 = "cool"
list1 = list(string1)
list1[1] = "u"
print("".join(list1))

执行时:

>>>cuol

相关问题 更多 >

    热门问题