Skip to content Skip to sidebar Skip to footer

Replacing Every Instance Of A Character In Python String

I have a game where the user guesses letters. They are shown a blank version of the mystery work (_____ for example, the _'s are equal to number of characters in the word). The pro

Solution 1:

answer = 'hippo'
fake = '_'*len(answer)   #This appears as _____, which is the place to guess
fake = list(fake)        #This will convert fake to a list, so that we can access and change it.
guess = raw_input('What is your guess? ')   #Takes inputfor k inrange(0, len(answer)):  #For statement to loop over the answer (not really over the answer, but the numerical index of the answer)if guess == answer[k]  #If the guess is in the answer, 
        fake[k] = guess    #change the fake to represent that, EACH TIME IT OCCURSprint''.join(fake)  #converts from list to string

This runs as:

>>>What is your guess?
p
>>>__pp_

To loop over everything, I did not use index, because index only returns the first instance:

>>>var = 'puppy'>>>var.index('p')
0

So to do that, I analyzed it not by the letter, but by its placement, using a for that does not put k as each letter, but rather as a number so that we can effectively loop over the entire string without it returning only one variable.

One could also use re, but for a beginning programmer, it is better to understand how something works rather than calling a bunch of functions from a module (except in the case of random numbers, nobody wants to make their own pseudo-random equation :D)

Solution 2:

Based on Find all occurrences of a substring in Python:

import re

guess = valid_guess()
matches= [m.start() for m in re.finditer(guess, word)]
if matches:
    formatchinmatches:
        attempt = attempt[0:match] + guess + attempt[match+1:]
        print("Letters matched so far: ", attempt)
else:
    .
    .
    .

Post a Comment for "Replacing Every Instance Of A Character In Python String"