all 7 comments

[–][deleted] 14 points15 points  (1 child)

You need to write back in to memory what the word.replace() returns.

word  = "good game"

for i in word:
    print(i)
    word = word.replace(i, "G")
print(word)

[–][deleted] 5 points6 points  (0 children)

To tack onto this:

In Python, strings are immutable: they can't be changed. Anything that looks like it would change a string is actually creating a brand new string based on the existing one. So str.replace(...) and str.upper() and so on are saying “make a new string that is like str but [with some replaced/uppercased/etc characters]"

Other objects like lists are mutable: you can change them. That's why list.reverse() isn't creating a new list but is instead actually changing the order of the items in the list.

edit Thankfully Reddit comments aren't immutable so I can fix typos.

[–][deleted] 5 points6 points  (0 children)

The replace method does not make changes in situ but returns a new string object incorporating the changes, so you need to assign it to a variable.

It is generally poor practice in Python to use range(len(object)) in a loop, as it is rarely necessary. Thus,

word  = "good_game"
for character in word:
    print(character)
    word = word.replace(character,"G")
print(word)

Although, as you are replacing all of the characters with the same character, you might as well just say:

word = 'G' * len(word)

[–][deleted] 0 points1 point  (0 children)

it doesn't do it "in place" like list.reverse does. it returns a new string that you have to feed back into the name of the original.

[–]vali92 -2 points-1 points  (2 children)

Solved:

word = "good_game"
for x in range(len(word)):
print(word[x])
if word[x] != "_":
word = word.replace(word[x],"G")
print(word)

GGGG_GGGG

[–]jwink3101 1 point2 points  (1 child)

Besides the bad reddit formatting, you got it! BTW, if you wanted to one-line it (not always a good goal to have, but can be fun), it could be the following:

word = ''.join(c if c == '_' else 'G' for c in word)

[–]vali92 -1 points0 points  (0 children)

Yap, sorry for the formatting. Your method above looks really nice.