-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?

Moduo
  • 623
  • 6
  • 17
Ben Ph
  • 9
  • 4
  • @PadraicCunningham: we need to have a primary source for all these duplicates [How best to redirect all duplicates of “Why didn't do anything/assign a result”?](http://meta.stackoverflow.com/questions/287093/how-best-to-redirect-all-duplicates-of-why-didnt-python-string-method-do-any) – smci Feb 28 '15 at 13:28

1 Answers1

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
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561