Replace all characters in a string with another character

Asked

Viewed 789 times

2

def getGuessedWord(secretWord, lettersGuessed):
    secretWord_copy = ""
    for i in secretWord:
        print(i)
        secretWord_copy = secretWord.replace(i," _ ")
    print(secretWord_copy)
secretWord = 'apple'  

I’m trying to replace every character of secretWord by " - "but the above code only replaces the last:

Appl _

What is wrong?

The result should be _ _ _ _ _

  • The final result should be "_____"?

  • @Barbetta: The result should be _ _ _ _ _

2 answers

4

I’m sorry to ask, but what would be the second parameter (lettersGuessed) of the function getGuessedWord. Because from what I am seeing it is not being used. And from what I understood of the function, just do the following to get the same result:

    def getGuessedWord(secretWord):
        print (len (secretWord) * ' _ ')
  • 1

    The question asked is in relation to the post, of course the best would be to use comments to answer questions from the question, but the answer is valid and the question asked I interpreted as a help to the author in relation to job creation

3


You are always overwriting secretword without modifying it.

def getGuessedWord(secretWord, lettersGuessed):
    secretWord_copy = ""
    for i in secretWord:
        print(i)
        secretWord_copy = secretWord.replace(i," _ ")
        secretWord = secretWord_copy
    print(secretWord_copy)
secretWord = 'apple'

Unchanged secretWord:

def getGuessedWord(secretWord, lettersGuessed):
    secretWord_copy = secretWord
    for i in secretWord:
        print(i)
        secretWord_copy = secretWord_copy.replace(i,"_")
    print(secretWord_copy)
    print(secretWord)
secretWord = 'apple'  
  • Actually I didn’t want to change the secretword, but only the copy. I need one more variable?

  • @Eds see the edit; just assign the original value to the copy at the beginning.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.