Reputation: 191
So, this functions is supposed to get a guess from a user. This guess should be one character and does not have any whitespaces in it.
The problem is, when I enter one space ' ' it returns 'You must enter a guess'. However, when I enter 2 spaces ' ' it returns 'You can only guess a single character'.
I need it to display 'You must enter a guess' instead. Whether the input contained one space or two or tap or two or even mix with tap and spaces. How can I do that?
def get_guess(repeated_guess):
while True:
guess = input('Please enter your next guess: ') # ask for input
guess.strip() # remove all spaces
guess = str(guess).lower() # convert it to lowercase string
if len(guess) > 1: # check if it's more than one character
print('You can only guess a single character.')
elif guess.isspace(' '):
print('You must enter a guess.')
elif guess in repeated_guess: # check if it's repeated
print('You already guessed the character:', guess)
else:
return guess
Upvotes: 1
Views: 661
Reputation: 1411
I'm not sure that I fully understand your question but, but I'll take a stab.
If you are looking for the user to input a single character as an input (that doesn't include white spaces), you should strip all of the white spaces from the input. guess.strip()
only removes the leading and trailing whitespaces.
Try using guess.replace(" ", "")
; this will remove all whitespaces from the user input.
Also, like others suggested, these methods return a new string with the appropriate characters stripped. Your code should look like guess = guess.strip()
Upvotes: 0
Reputation: 36
Your problem is that you check the length of the string before checking if it is only white space. A string with 2 spaces will be considered a 2 character string, and since that if statement will be evaluated first it returns the multi character print statement.. If you reorder the code so that it checks if the string is only white space first it will instead prioritize that print statement over the other.
Upvotes: 0
Reputation: 357
You should put the guess new value after you strip it guess=guess.strip()
Upvotes: 0
Reputation: 304147
An easy way without regex.
guess = ''.join(guess.split())
This removes whitespace from anywhere in the string. strip
only removes from the ends of the string until the first non-whitespace character.
Upvotes: 1
Reputation: 129011
guess.strip()
returns the stripped string; guess
remains unchanged. You need to reassign it:
guess = guess.strip()
Upvotes: 1