1

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
0

5 Answers 5

1

guess.strip() returns the stripped string; guess remains unchanged. You need to reassign it:

guess = guess.strip()
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

You should put the guess new value after you strip it guess=guess.strip()

Comments

0

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.

Comments

0

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.