-1

So I have a function guess_check(guess) that is invoked by prompt() function

Prompt() invokes guess_check() so that guess is a one work string containing an alphabet character.

word is a variable = "placeholder"

Below is the code that I'm having trouble with:

if guess in word:
    word.replace(guess, '*')
print word

If I make guess = "a" I would anticipate word = "pl*ceholder", but it doesn't change.

Why does the word variable not change, and how can I get it to change as I want?

1

1 Answer 1

3

Strings are immutable, so you need to reassign the result of the method call:

if guess in word:
    word = word.replace(guess, '*')
print word

As a rule of thumb, methods on immutable objects (strings, tuples etc.) usually return a new value whereas methods on mutable objects (lists, dicts, sets etc.) modify the object in-place, which is why you can do

>>> l = [3, 2, 4, 1]
>>> l.sort()
>>> l
[1, 2, 3, 4]

but not (which is another typical beginner's mistake)

>>> l = l.sort()

because list.sort() doesn't return anything (which means it returns None), so that line would assign None to l:

>>> print l
None

Not the answer you're looking for? Browse other questions tagged or ask your own question.