简体   繁体   中英

How do I replace a string at multiple indices (Python)?

I have a string and I want to replace characters at certain indices of that string. But I only know how to replace a character if I got one index using:

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

pos in this case is the index. But when I now have a list of multiple indices (so pos is a list now), it does not work, because slice indices must be integers.

Here is some more code to give mor context:

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)

I must say your code is a bit clunky and hard to understand.

But if you want to apply the same operation to a list of indices, then just iterate over your list of indices and apply the same logic:

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:]

You could simply iterate over the array:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM