check user_input with if token in a loop - python

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.

Related

Can't wrap my head around how to remove a list of characters from another list

I've been able to isolate the list (or string) of characters I want excluded from a user entered string. But I don't see how to then remove all these unwanted characters. After I do this, I think I can try joining the user string so it all becomes one alphabet input like the instructions say.
Instructions:
Remove all non-alpha characters
Write a program that removes all non-alpha characters from the given input.
For example, if the input is:
-Hello, 1 world$!
the output should be:
Helloworld
My code:
userEntered = input()
makeList = userEntered.split()
def split(userEntered):
return list(userEntered)
if userEntered.isalnum() == False:
for i in userEntered:
if i.isalpha() == False:
#answer = userEntered[slice(userEntered.index(i))]
reference = split(userEntered)
excludeThis = i
print(excludeThis)
When I print excludeThis, I get this as my output:
-
,
1
$
!
So I think I might be on the right track. I need to figure it out how to get these characters out of the user input. Any help is appreciated.
Loop over the input string. If the character is alphabetic, add it to the result string.
userEntered = input()
result = ''
for char in userEntered:
if char.isalpha():
result += char
print(result)
This can also be done with a regular expression:
import re
userEntered = input()
result = re.sub(r'[^a-z]', '', userEntered, flags=re.I)
The regexp [^a-z] matches anything except an alphabetic character. The re.I flag makes it case-insensitive. These are all replaced with an empty string, which removes them.
There's basically two main parts to this: distinguish alpha from non-alpha, and get a string with only the former. If isalpha() is satisfactory for the former, then that leaves the latter. My understanding is that the solution that is considered most Pythonic would be to join a comprehension. This would like this:
''.join(char for char in userEntered if char.isalpha())
BTW, there are several places in the code where you are making it more complicated than it needs to be. In Python, you can iterate over strings, so there's no need to convert userEntered to a list. isalnum() checks whether the string is all alphanumeric, so it's rather irrelevant (alphanumeric includes digits). You shouldn't ever compare a boolean to True or False, just use the boolean. So, for instance, if i.isalpha() == False: can be simplified to just if not i.isalpha():.

Remove some specific text from an input?

say_d = ["say", "tell me"]
a = input("Please Type An Action For Me To Do: ")
if any(word in a for word in say_d):
print(a)
This is the program that prints out the typed input, if any keyword from say_d is in it. But it will also print the keyword. Is there any way to remove the keyword from the supposed output? Like:
say_d = ["say", "tell me"]
a = input("Please Type An Action For Me To Do: ")
if any(word in a for word in say_d):
print(a-say_d)
You can use either regex or str.replace to replace the common words with empty string:
import re
say_d = ["say","tell me"]
a = (input("Please Type An Action For Me To Do: "))
if any(word in a for word in say_d):
print(re.sub('|\b'.join(say_d), '', a))
But Note that if you want to remove the common words if thery exist in input, you don't need to use any, for both functions (re.sub and str.replace) replace the string only of they exist in your text.
Also, the part word in a will check the membership within the entire input string, not its words. That says, if one of the words within the input string is contain a word inside say_d it will return True. Like sayulita which is contain the word say.
For getting ride of this problem you can again check the membership by splitting the input string and then looping over it or use regex.
This is what you looking for:
say_d=["say","tell me"]
a=(input("Please Type An Action For Me To Do: "))
if any(word in a for word in say_d):
set2 = set(say_d)
result = [element for element in a if element not in set2]
print(list(result))
Without any input and output in question, i assume that you want to remove any candidate word(which in list say_d) from input string, so maybe it can be as simple as below:
say_d=["say","tell me"]
a=(input("Please Type An Action For Me To Do: "))
ret = reduce(lambda r, w: r.replace(w, ''), say_d, a)
if len(ret) != len(a):
print ret

re.rompile returns true with false, not allow symbols

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.

How to check if every character of the string is different?

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!")

how to get certain words from user input

Hello i am trying to make my program check for certain words in the user input. For example: The user types "add the numbers 6+6" what the programs does is it has a dictionary and checks the words in the dictionary and compares them to the words in the user input this example is "add". If the word add is in the user input then it checks for numbers and also math symbols this example is "6+6" then it outputs the answer?
I have tried:
if test == "add":
do something
but this will not work unless the word "add" is all by itself. any help is very much appreciated.
It will work only in the cases like add 6+6 or 6+6 add or add <some_text> 6+6 etc.
string = input()
if 'add' in string:
string = string.split('+')
no1 = int(string[0].split()[-1])
no2 = int(string[1].split()[0])
print(no1 + no2)
You can loop through the input words and check them in your dictionary like
for word in input:
if word in dic:
pass
fail
You can use the string.split() to split up the text into each word.
Then you can test each word individually for key words.
Details: http://docs.python.org/2/library/string.html
Look up the split method.
I'm pretty sure the split method by default returns a list of words split up by white space characters. So for example:
test_list = input.split()
test_list[1] should be 'add'
Best way to find out is to test it yourself, but I think it is something along those lines.
Cheers

Categories