Python Replace Blanks With Letter - python

I want the letters the user types (granted that they're in the 'letters') to replace the blanks in their correct sequential position (I don't want 'agbdf__'), and stop when all the letters are typed in. As the code is now, it requires letters to be typed multiple times, and it stops if the letter 'g' is typed seven times. This is a part of a hangman code I'm trying to implement. If anyone could post the right way to program this (not just a tip, because I most likely won't be able to figure out how to implement it), it would be much appreciated.
letters='abcdefg'
blanks='_'*len(letters)
print('type letters from a to g')
print(blanks)
for i in range(len(letters)):
if letters[i] in input():
blanks = blanks[:i] + letters[i] + blanks[i+1:]
print(blanks)

Change your loop to:
for i in range(len(letters)):
letter = raw_input()
index = letters.index(letter)
blanks = blanks[:index] + letter + blanks[index + 1:]
print blanks
You are not replacing the correct blank/underscore, you are just sequentially replacing them. Instead you need to find the correct blank to replace, and then replace that. Also don't expect this code to be running infinitely until the blanks is completely filled. If you want that, you can figure that out I guess (as your question is specific to replacing correct letters). Also you might want this program should handle inputs other than 'abcdef' too :).

You could use a list comprehension for this. Here's an example:
letters = 'abcdefg'
typed = raw_input('Type the characters a through g: ')
print ''.join(s if s in typed else '_' for s in letters)
Sample Output:
Type the characters a through g: abdef
ab_def_
Here's a more complete/advanced hangman example: https://gist.github.com/dbowring/6419866

letters = 'abcdefg'
print('type letters from a to g')
all_letters = list(letters)
blanks = ['_'] * len(letters)
while True:
guessed_letter = input("guess > ")
while guessed_letter in all_letters:
index = all_letters.index(guessed_letter)
all_letters[index] = None
blanks[index] = guessed_letter
output = ''.join(blanks)
print(output)
if letters == output:
print("gg")
break
Or if you prefere a more stringy version
letters = 'abcdefg'
print('type letters from a to g')
all_letters = list(letters)
blanks = '_' * len(letters)
while True:
guessed_letter = input("guess > ")
while guessed_letter in all_letters:
index = all_letters.index(guessed_letter)
all_letters[index] = None
blanks = blanks[:index] + guessed_letter + blanks[index+1:]
print(blanks)
if letters == blanks:
print("gg")
break

Related

How to replace the specified dash with the letter

I wish to write a hangman program and in order to do so, I have to replace the hash ('-') letter(s) with the user's guessed letter (guess). But when I run the code, it replaces all the hashes with the user's guess letter.
The code seems okay but I don't get the desired result.
words is a list of words I have written before the function.
def word_guess():
random.shuffle(words)
word = words[0]
words.pop(0)
print(word)
l_count = 0
for letter in word:
l_count += 1
# the hidden words are shown a '-'
blank = '-' * l_count
print(blank)
guess = input("please guess a letter ")
if guess in word:
# a list of the position of all the specified letters in the word
a = [i for i, letter in enumerate(word) if letter == guess]
for num in a:
blank_reformed = blank.replace(blank[num], guess)
print(blank_reformed)
word_guess()
e.g: when the word is 'funny', and guess is 'n', the output is 'nnnnn'.
How should I replace the desired hash string with guess letter?
it replaces all the hashes
This is exactly what blank.replace is supposed to do, though.
What you should do is replace that single character of the string. Since strings are immutable, you can't really do this. However, lists of strings are mutable, so you could do blank = ['-'] * l_count, which would be a list of dashes, and then modify blank[num]:
for num in a:
blank[num] = guess
print(blank)
A couple things to note:
inefficient/un-pythonic pop operation (see this)
l_count is just len(word)
un-pythonic, unreadable replacement
Instead, here's a better implementation:
def word_guess() -> str:
random.shuffle(words)
word = words.pop()
guess = input()
out = ''
for char in word:
if char == guess:
out.append(char)
else:
out.append('-')
return out
If you don't plan to use the locations of the correct guess later on, then you can simplify the last section of code:
word = 'hangman'
blank = '-------'
guess = 'a'
if guess in word:
blank_reformed = ''.join(guess if word[i] == guess else blank[i] for i in range(len(word)))
blank_reformed
'-a---a-'
(You still have some work to do make the overall game work...)

how to remove letter from one list to the other randomly but to the right location

I just started to learn python and as part of my learning i am trying to make simple programs.
so i tried to make an hangman game and i am stuck.
i cant think of a better way to identify the letter in the word the player need to guess - - and adding the letter at the right place in var of what the player guess so far.
The code:
import random
list_of_words = ["door", "house", "work", "trip", "plane", "sky", "line", "song", "ever","life"]
random_word = list_of_words[random.randint(0, len(list_of_words) - 1)]
guessed_word = "_" * len(random_word)
print("Hello!, welcom to my hangman Game")
print("try to guess what word could that be??? ")
print(guessed_word)
guessed_word = guessed_word.split()
random_word = list(random_word)
print(random_word, guessed_word)
while len(random_word) != 0:
letter = input("guess a letter >>>... ")
if letter in random_word:
print(f"YAY! thats right, {letter} is in the word")
index = random_word.index(letter)
random_word.remove(letter)
guessed_word[index] = letter
print("this is your word now >> ", guessed_word)
else:
print("the word isnt there")
print("yay, you found the word")
So, the code is running good and it identify when the player finished choosing all the right letters. the problem is how to copy the word and show players progress. so at the start it puts the letter in the right place, but after that it doesn't change the letter location.
Couple things wrong here.
finding only one occurrence of the letter (door would only find the first o)
Removing items loses track of the index
guessed_word splitted wrong
These issues fixed:
import random
list_of_words = ["door", "house", "work", "trip", "plane", "sky", "line", "song", "ever","life"]
random_word = list_of_words[random.randint(0, len(list_of_words) - 1)]
guessed_word = "_" * len(random_word)
print("Hello!, welcom to my hangman Game")
print("try to guess what word could that be??? ")
# Convert to list first
guessed_word = list(guessed_word)
# Print separated with spaces second
print(' '.join(guessed_word))
random_word = list(random_word)
# Check if the guessed word is the same as the random word, if it is, the word is fully guessed
while random_word != guessed_word:
letter = input("guess a letter >>>... ")
if letter in random_word:
print(f"YAY! thats right, {letter} is in the word")
# find all indices of the letter
indices = [i for i, x in enumerate(random_word) if x == letter] # * see notes
# Update all indices of the guessed word with the letter
for i in indices:
guessed_word[i] = letter
# Don't remove the letter from the random word
# Print with spaces, because it's nicer that way!
print("this is your word now >> ", ' '.join(guessed_word))
else:
print("the word isnt there")
print("yay, you found the word")
Hope this helped! Have fun using python!
Notes:
List comprehension can be scary, have a look at this
You just need to replace
guessed_word = guessed_word.split()
with:
guessed_word = list(guessed_word)
and the reason why on example:
>>> x="work"
>>> x.split()
['work']
>>> list(x)
['w', 'o', 'r', 'k']
>>>
x.split() splits sentence per white space as a delimiter - you want to split it letter by letter instead.

Trying to allow user to use either capital or lowercase letters in Hangman code

I'm writing a hangman game in python for class. The user is told they have guessed incorrectly when they put a lower case when it is upper case and vice versa. Also when there is a space in the input it displays as an underscore (_) as well.
def gettingWord(theWord, lettersGuessed):
count = 0
blank = ['_ '] * len(theWord)
for i, c in enumerate(theWord):
if c in lettersGuessed:
count = count + 1
blank.insert(count-1,c)
blank.pop(count)
if count == len(theWord):
return ''.join(str(e) for e in blank)
else:
count = count + 1
blank.insert(count-1,'_')
blank.pop(count)
if count == len(theWord):
return ''.join(str(e) for e in blank)
The code itself works I just want to know how I can fix this issue. Can anyone help?
If I'm understanding correctly you want the user to be able to use uppercase and lowercase characters without affecting the result. If that's the case then you can use string's method lower() in order to turn each character the user guesses lowercase. In your function you could just add these two lines in the beginning:
theWord = theWord.lower()
lettersGuessed = [c.lower() for c in lettersGuessed]
First you turn the word to guess into lowercase, and then you turn each character in lettersGuessed lowercase (assuming lettersGuessed is a list of characters, if it's a string then you can just write lettersGuessed = lettersGuessed.lower()). This way all characters will be lowercase so the answer will depend on the character only and not on the casing.
Convert both the character and the letters guessed to lowercase to ignore case. If the character is whitespace, you also want to insert the character so you should add or not c.strip() to the if check to also insert the character if its whitespace.
Also, just to reduce code duplication, you should try and remove the duplicate code out of the if/else blocks, this will help with maintaining this or changing the logic in the future.
def gettingWord(theWord, lettersGuessed):
count = 0
blank = ['_ '] * len(theWord)
for c in theWord:
if c.lower() in lettersGuessed.lower() or not c.strip():
blank.insert(count, c)
else:
blank.insert(count, '_')
count = count + 1
blank.pop(count)
if count == len(theWord):
return ''.join(str(e) for e in blank)
Convert everything to lowercase, and strip spaces.
All the words in the word bank should be lowercase
When getting input:
letter = input('Enter a letter: ').lower().strip()
That should fix your problems with spaces and casing.

Python hangman without lists

I need a simple Python Hangman program without using Lists - It is just one word
HAPPY - this program works - BUT...
This is what I did, with Lists - but teacher said Lists are not allowed
We do not have to draw hangman - we just prompt for the letters - print the "-" for each letter to show length of word.
def main():
secretword = "HAPPY"
displayword=[]
displayword.extend(secretword)
for I in range (len(displayword)):
displayword[I]="_"
print ('current word
')
print (' '.join(displayword))
count = 0
while count < len(secretword):
guess = input('Please guess a etter: ')
for I in range(len(secretword)):
if secretword[I] == guess:
displayword[I] = guess
countr - count + 1
print (' '.join(displayword))
print (congratulations you guess the word')
main()
If you don't like the code - that's fine. This is how our teacher is requiring us to do this. I can see it is not like others do it. I only left out the comments - that are also required on every line of code
One solution to your problem would be to use two strings, secretword, which is the word you're looking for and displayword which is what the user sees so far, the combination of letters and -. Every time you enter a letter, the program checks if the secretword contains that letter and if it does, it updates the character of the specific index in displayword:
def main():
secretword = "HAPPY"
length = len(secretword)
displayword = '-' * length
count = 0
while count < length:
guess = input("Please guess a letter: ")
for i in range(length):
if secretword[i] == guess:
displayword[i] = guess
count += 1
print(displayword)
print("Congratulations, you guessed the word.")
main()

how do i unhide spaces between words in a hangman game?

I am making a hangman game, but there's something i can't figure out.
I am able to hide the letters using
guessed = "_"*len(guess)
but it also hides the spaces. for example if my word is 'the avengers' it will hide 12 characters instead of 11. how do unhide/leave the spaces alone? this is what i have so far:
def getHiddenWord():
guess = getRandomWord().lower()
guessed = "_"*len(guess)
if "_" in guessed is " ":
print(guessed.replace("_", " "))
else:
print("The Word is:", guessed)
return guessed
Use re.sub
guessed = re.sub(r'\S', '_', guess)
\S would match any non-space character. So the above re.sub function would replace any non-space character from the input string with _.
Example:
>>> import re
>>> s = 'the avengers'
>>> re.sub(r'\S', '_', s)
'___ ________'
>>>
or
>>> ''.join(['_' if not i.isspace() else i for i in s])
'___ ________'
>>>
A simple way to do that:
def getHiddenWord(guess):
guessed = ''
for c in guess.lower():
if c != ' ':
guessed += '_'
else:
guessed += ' '
return guessed
The problem with your approach is that you use this:
guessed = "_"*len(guess)
It takes the whole length of the string and the empty space is also counted. If for some reason you need to exclude empty space in the count of len you need to use this:
guessed = "_" * (len(guess) - guess.count(' '))
But in your case you most likely don't need it.
Also note that the function getHiddenWord(guess) does not change your original word but creates a new one and returns it.

Categories

Resources