Replace all characters in a string with another character

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 with "-" but the above code only replaces the last one:

appl _

What's wrong?

The result should be _ _ _ _ _ _

    
asked by anonymous 22.04.2018 / 21:04

2 answers

3

You're always replacing 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'

Without changing 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'  
    
22.04.2018 / 21:10
3

I'm sorry for the question, but what would the second parameter (lettersGuessed) of the getGuessedWord function look like? Because from what I'm seeing she's not being used. And from what I understood from the function, just do the following to get the same result:

    def getGuessedWord(secretWord):
        print (len (secretWord) * ' _ ')
    
06.05.2018 / 02:44