How to replace a letter in a specific place inside a string in python, without transforming into a list?

StackOverflow https://stackoverflow.com/questions/23232914

Question

I want to replace a specific location on a string but it is replacing the whole string

Relevant part of the code:

userInput = "i"
word = "university"
answer = "*" * len(word)

if userInput in word:
        for letter in word:
            if letter == userInput:
                location = word.find(userInput)
                answer = answer.replace(answer[location],userInput)
        print(answer)

Current Output:

iiiiiiiiii

Desired Output:

**i****i**
Was it helpful?

Solution

what x.replace(a, b) does is replace any occurrences of the value a in x with b so answer.replace(answer[location], userInput) just replaces all * with the value of userInput because answer[location] is *. In other words, it's not possible to specify the index of what you want to replace like that.

So instead of:

answer = answer.replace(answer[location],userInput)

do

answer = answer[:location] + userInput + answer[location + 1:]

UPDATE:

The rest of the logic was also flawed, so this will work:

userInput = "i"
word = "university"
answer = "*" * len(word)

for location, letter in enumerate(word):
    if letter == userInput:
        answer = answer[:location] + userInput + answer[location + 1:]

This also contains the suggestion to use enumerate() by SethMMorton, which turns out to be unavoidable :)

enumerate('abc') will yield [(0, 'a'), (1, 'b'), (2, 'c')], which means you won't need to use find as you'll already have the location (index) of the letter available right away.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top