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

문제

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**
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top