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
guess.strip() returns the stripped string; guess remains unchanged. You need to reassign it:
guess = guess.strip()
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.
You should put the guess new value after you strip it
guess=guess.strip()
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.
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()
Related
I'm having trouble trying to execute this code, I want the user to input a value, the program checks if that value is a string then it returns the length.
If the value contains whitespaces the programs remove the whitespace and print the length.
But if it contains any integer values the program returns "No Integers is Allowed"
This is the code:
def length(Name):
long = len(Name)
return long
new_length = input("Please Enter Your name You can use Spaces: ")
value1 = new_length
if value1.isspace() == True:
print("This is Before Removing Spaces: " + value1)
value2 = value1.replace(" ", "")
print("This is After Removing Spaces: " + value2)
elif value1.isalpha() == True:
print("Here is The Length: ", length(value1))
elif value1.isdigit() == True:
print("Integers are not allowed! ")
else:
print("There's someting wrong with "+ value1)
So if you can help me with that I appreciate it.
Thanks
I don't think the str.isspace, str.isalpha and str.isdigit methods do what you expect them to do. To start with, they all test if all the characters in the string you enter are of the type that is described in their name. Your code seems to be expecting them to be return True if any of the characters match. That is, if there are any spaces, you want to remove them and show the two lengths, before and after.
There's no single string method that will do that test for you in Python. You could use regular expressions (which are more powerful, but much more complicated), or you could write some slightly more elaborate code to do the test. I'd suggest using the any function, and passing it a generator expression that calls the method you want on each character in the string.
if any(c.isspace() for c in user_str):
...
This may not be exactly what you want for all of your tests. The desired logic of your code is not entirely obvious, as there are a number of corner cases that your output doesn't specifically address. Is a string that contains both letters and numbers valid? How about one that has spaces in between numbers, but no letters at all? You may need to reorder the conditions of your if/elif/else statements so that they match what you intend.
I'd also note that the variable name you used for user input, new_length, is very misleading. It's not a length, its the string you want to measure the length of! It's a lot easier to make logic errors about variables that have misleading or unclear variable names, so taking time to go back and reconsider names you chose earlier is sometimes a good idea, as it can improve the clarity of your code a lot! Descriptive variable names are good, but it's a tradeoff between clarity and brevity, as long names are tedious to type (and prone to typos). They also can lead to line length issues, which can make it less convenient to see all your code on your editor screen at once.
You can use this function to check if the input string contains a number:
def hasNumbers(inputString):
return any(char.isdigit() for char in inputString)
It returns true if there is a number and false if there is not.
As for the whitespaces you can ommit isspace(). Using replace() alone will do the job, even if there are no whitespaces.
stri='jshsb sjhsvs jwjjs'
stri=stri.replace(' ','')
I suggest reading the documentation in these cases. For isspace, note here that
Return True if there are only whitespace characters in the string and there is at least one character, False otherwise.
That is, if there's anything that's not a space there, it will be False. Which is annoying, but why check in the first place? Just do the replacement! If there's no whitespace, it won't do nothing. If you need to print those statements, you can do
if ' ' in value1:
...
(of course, this doesn't consider all the possible kinds of whitespaces, check the other answers for doing the for loop if you need that)
Next, I believe you need to remove the elifs and just use if statements, since note that if you input a name with a space, it will print the name with the spaces removed... and nothing after that. Not even if it has integers in it. This is because elif statements don't execute once another above them did.
There are many other things you need to consider, but these two I think you should consider first. Hope it's useful!
You can use the re module in Python to check for white spaces in your string. It returns True if there are white spaces and False otherwise.
import re
def length(Name):
long = len(Name)
return long
new_length = input("Please Enter Your name You can use Spaces: ")
value1 = new_length
if re.search('\s', value1):
print("This is Before Removing Spaces: " + value1)
value2 = value1.replace(" ", "")
print("This is After Removing Spaces: " + value2)
print("Here is The Length: ", length(value2))
elif value1.isalpha() == True:
print("Here is The Length: ", length(value1))
elif value1.isdigit() == True:
print("Integers are not allowed! ")
else:
print("There's someting wrong with "+ value1)
More information
Below is my code. I am in the process of making a small program that finds Palindromes. I want the program to take user input, save it to a variable, and then check for any spaces. If it finds a space to save its index, and then to take it out to check for a Palindromes. Out of curiosity and to further my programming skills, I want to be able to add the space back later while the word is in reverse. For example, nurses run = nursesrun backward and forwards, but I also want to display it backward and add the space back.
word = input("Please enter a word")
storeVal = word.count(" ")
print()
newWord = word.replace(" ", "")
print(newWord)
print()
while True:
if newWord == "":
print("Sorry, but you did not enter a word")
break
elif newWord == newWord[::-1]:
#use the index storeVal and add it in the string to put a space back
print(" is a palidrone")
break
elif newWord != newWord[::-1]:
print("This is not a palidron")
break
else:
print("You have reached an error")
Also, if you have any suggestions for how I can improve my ability to ask this question or a better way I can write this question, please let me know. Thank you for reading.
Just reverse word instead of reconstructing the modified newWord!
print("{} is a palidrone".format(word[::-1]))
Also storeVal in your example isn't storing the index of the space -- it's storing the number of spaces in your input string.
As per the other answer, just for displaying you can print word instead of newWord. But if you want to learn how get the original positions of spaces, here are a few hints:
word.find(" ") will give you the index of the first space or -1 if none found, you can save it into a list, and than call word.find(" ", space_index + 1) to call the next one, where space_index is the index of last found space, until you get -1 which means no more spaces
another, more educated (to my opinion), would to enumerate the string and collect all indexes for spaces in a list using list comprehension (or set, of you don't care about the order).
Im trying to use regex do check a variable for accepted letters and numbers. This is my def:
def special_match(strg, search=re.compile(r'[a-z0-9]').search):
if bool(search(strg)) is True:
print ('Yes: ' + strg)
elif:
print ('nej: ')
while 1:
variabel = raw_input('Enter something: ')
special_match(variabel)
sys.exit()
And it seems that is accepts not allow symbols in combination with allow symbols:
Enter something: qwerty
Yes: qwerty
Enter something: 1234
Yes: 1234
Enter something: !!!!
nej!
Enter something: 1234qwer!!!!
Yes: 1234qwer!!!!
Enter something:
The last one should not be accepted.. What I'm doing wrong??
All your regular expression search is doing is checking to see if at least one of the characters is present.
If you want to require that the entire string contains nothing but those characters, then you can use:
r'^[a-z0-9]*$'
That anchors the pattern at both the start and end of the string, and only matches if all of the characters in between are in the specified set of characters.
Note that this will also match the empty string. If you wish to require at least one character, then you can change the * to +.
the search method finds for regex you gave and if it finds then returns a Match object here 1234qwer!!! has [a-z0-9] but !!!! doesnt.
Try a!!!. that will also return True.
You could try doing
re.search(r"[^a-z0-9]",word)
and if this returns True that means your word has something other than digits and alphabets and that should be rejected.
NOTE: ^ means not.
The only thing that regex does is check that there is a number or a letter in your string. If you want to check that it only has numbers and letters, you need to anchor your pattern at the start and end, and add a repeat: r'^[a-z0-9]+$'
Note though that there is no need to use regex for this: the string isalnum() method will do the same thing.
There are a couple of other odd things in your code; you should definitely not be compiling a regex in the function signature and passing on the resulting search method; also you should not be converting the result to bool explicitly, and you should not compare bools with is True. A more Pythonic version, assuming you wanted to stick to the regex, would be:
def special_match(strg, search=None):
if not search:
search = re.compile(r'[a-z0-9]').search
if search(strg):
print ('Yes: ' + strg)
else:
print ('nej: ')
Also note elif is a syntax error on its own.
I was just wondering, how to check if I ask a person to input a string, how do I check if every character inside that string is different?
For an example:
string = str(input("Input a string: ")
I would like to do it with a while loop. So, if two characters in a string are different, it stays in the loop and prompts the user to input the string again.
If I understand your question correctly, you want to reject any string that contains more than one copy of the same character. If a string with duplicated characters is entered, you want to repeat the prompt and get another input.
The easiest way to do the duplicate check is to create a set from your string and then check if the set has the same length as the original. If there were any duplicates in the string, they'll be present only once in the set.
while True:
input_string = input("Enter a string")
if len(set(input_string)) == len(input_string):
break
print("Please avoid repeating any characters")
You could also try this:
while True:
b = input("Enter a string: ")
if all([b[i] not in b[:i] + b[i+1:] for i in range(len(b))]):
break
print("Please try again!")
I am trying to write a function that checks my input to see whether I have entered the character '?'.
This is what I got so far:
def check_word():
word = []
check = 0
user_input = input('Please enter a word that does not contain ?: ')
for token in user_input.split():
if token == '?':
print('Error')
check_word()
My input: hello?
It is supposed to show 'Error'. But it doesn't show anything. Could you please tell me what wrong it is in my code.
I would use the in operator to do this
def check_word(s):
if '?' in s:
print('Error')
For example
>>> check_word('foobar')
>>> check_word('foo?')
Error
The problem is how you split the string of the user_input.
user_input.split():
The example doesn't contain whitespaces so the condition isn't met. If you want for example to check a sentence with spaces, you should split it like this: user_input.split(' ') to split it on the spaces.
But for this example you have two choices:
1) You can just iterate over the input itself because you want to check every char in the string for whether it's a ?.
That is, change user_input.split(): into simply user_input without splitting. This option is good if you might ever want to add some sort of action for each char.
2) It's very easy just to use in, like this:
if '?' in s:
print('There is a question mark in the string')
This is a very simple solution that you can expand and check for other chars in the string as well.
It's because user_input.split() splits the user_input by whitespace. Since hello? does not contain any whitespaces, token is equal to your input and the loop is executed once.
You should iterate over user_input instead, or simply check if '?' in user_input.