为了账号安全,请及时绑定邮箱和手机立即绑定

如何替换多个索引处的字符串(Python)?

如何替换多个索引处的字符串(Python)?

缥缈止盈 2022-10-06 19:39:29
我有一个字符串,我想替换该字符串某些索引处的字符。但我只知道如何替换一个字符,如果我得到一个索引使用:word = word[:pos] + 'X' + word[pos + 1:]pos 在这种情况下是索引。但是当我现在有一个多个索引的列表时(所以 pos 现在是一个列表),它不起作用,因为切片索引必须是整数。这里有一些更多的代码来提供 mor 上下文:string = 'HELLO WORLD'secretword = ''.join('_' for c in string)while True:    userinput = input("Give me a letter\n").upper()    if len(userinput) == 1:        if userinput in string:            pos = [i for i in range(len(string)) if string[i] == userinput]            secretword = secretword[:pos] + userinput + secretword[pos + 1:] #this does not work            print(secretword)
查看完整描述

2 回答

?
HUX布斯

TA贡献1876条经验 获得超6个赞

我必须说您的代码有点笨拙且难以理解。


但是,如果您想将相同的操作应用于索引列表,则只需遍历您的索引列表并应用相同的逻辑:


pos_list = [i for i in range(len(string)) if string[i] == userinput]

for pos in pos_list:

    word = word[:pos] + 'X' + word[pos + 1:]


查看完整回答
反对 回复 2022-10-06
?
天涯尽头无女友

TA贡献1831条经验 获得超9个赞

您可以简单地遍历数组:


while True:

    userinput = input("Give me a letter\n").upper()

    if len(userinput) == 1:

        if userinput in string:

            pos = [i for i in range(len(string)) if string[i] == userinput]

            for p in pos:

                secretword = secretword[:p] + userinput + secretword[p+1:]

            print(secretword)


查看完整回答
反对 回复 2022-10-06
  • 2 回答
  • 0 关注
  • 85 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号