1

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)
2
  • In this case, the easiest thing would probably be to use a list. Commented Apr 13, 2020 at 14:08
  • why not simply using the replace function? Commented Apr 13, 2020 at 14:17

2 Answers 2

1

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:]
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.