Python - Check if a user input is in another user input - python-3.x

Python 3.5
I am writing a program that essentially asks the user to input a sentence (no punctuation). Then it will ask for the user to input a word. I want the program to identify whether or not that word is in the original sentence (I refer to the sentence as string 1 (Str1) and the word as string 2 (Str2)). With the current code I have, it will only ever tell me that the word has been found and I can't seem to find a way to fix it.
str1 = input("Please enter a full sentence: ")
print("Thank you, You entered:" , str1)
str2 = input("Now please enter a word included in your sentence in any way you like: ")
if (str2,str1):
print("That word was found!")
else:
print("Sorry, that word was not found")
If anyone has any advice on that might help me and anyone else interested in this topic then that would be greatly appreciated! :)
Although as this is a learning process for me, i don't really want straight forward "here's the code you should have..." but if that is all that can be offered then i would be happy to take it.

if str2 in str1:
print("That word was found!")
else
print("Sorry, that word was not found")
Is this what you are looking for ?
The in checks if str2 is literally in str1. Since str1 is a list of words it checks if str2 is inside str1.

The answer provided works ok, but if you want word matching, will provide a false positive given:
EDIT: just spotted the prompt asks for a word in the sentence... In my experience, these sorts of things are most prone to breakage when they interact with a human, so I try to plan accordingly.
str1 = "This is a story about a man"
str2 = "an"
where:
broken_string = str1.split()
if str2.lower() in [x.lower() for x in broken_string]:
print("The word {} was found!".format(str2))
else:
print("{} was not found in {}.".format(str2, str1))
Gets a little more complicated (fun) with punctuation.

Related

Python Error message for entering a number instead of a letter

I just started my programming education with python in school. One of the programs I started with simply asks you your name and then repeats it back to you. I'd like some help with getting an error message to show up if you put in a number rather than letters.
This is what I have:
while True:
name = input("What is your full name? ")
try:
n = str(name)
except ValueError:
print("Please enter your name in letters, not", repr(name))
continue
else:
break
print(name)
You can check the name if only contains letters by using string.isalpha()
in your case you name it n so n.isalpha() will return True or False
for more information:
How can I check if a string only contains letters in Python?

check string by iterate

str1=input()
for i in str1:
if i=='a'
print('word:a')
else:
continue
print('without:a')
I input one word. And i want to check if the word content letter:'a'.
use print() in the end.
The problem is I do not know how to excute the code after continue
The result i want like this:
ex1:
apple
word:a
ex2:
home
without:a
Assuming you are required to use a for loop rather than just check 'a' in str1, use a for-else
str1=input()
for i in str1:
if i=='a'
print('word:a')
break
else:
print('without:a')
if 'a' in input():
print('word:a')
else:
print('without:a')
print("word:a" if 'a' in input() else "without a")

Expected str instance, int found. How do I change an int to str to make this code work?

I'm trying to write code that analyses a sentence that contains multiple words and no punctuation. I need it to identify individual words in the sentence that is entered and store them in a list. My example sentence is 'ask not what your country can do for you ask what you can do for your country. I then need the original position of the word to be written to a text file. This is my current code with parts taken from other questions I've found but I just can't get it to work
myFile = open("cat2numbers.txt", "wt")
list = [] # An empty list
sentence = "" # Sentence is equal to the sentence that will be entered
print("Writing to the file: ", myFile) # Telling the user what file they will be writing to
sentence = input("Please enter a sentence without punctuation ") # Asking the user to enter a sentenc
sentence = sentence.lower() # Turns everything entered into lower case
words = sentence.split() # Splitting the sentence into single words
positions = [words.index(word) + 1 for word in words]
for i in range(1,9):
s = repr(i)
print("The positions are being written to the file")
d = ', '.join(positions)
myFile.write(positions) # write the places to myFile
myFile.write("\n")
myFile.close() # closes myFile
print("The positions are now in the file")
The error I've been getting is TypeError: sequence item 0: expected str instance, int found. Could someone please help me, it would be much appreciated
The error stems from .join due to the fact you're joining ints on strings.
So the simple fix would be using:
d = ", ".join(map(str, positions))
which maps the str function on all the elements of the positions list and turns them to strings before joining.
That won't solve all your problems, though. You have used a for loop for some reason, in which you .close the file after writing. In consequent iterations you'll get an error for attempting to write to a file that has been closed.
There's other things, list = [] is unnecessary and, using the name list should be avoided; the initialization of sentence is unnecessary too, you don't need to initialize like that. Additionally, if you want to ask for 8 sentences (the for loop), put your loop before doing your work.
All in all, try something like this:
with open("cat2numbers.txt", "wt") as f:
print("Writing to the file: ", myFile) # Telling the user what file they will be writing to
for i in range(9):
sentence = input("Please enter a sentence without punctuation ").lower() # Asking the user to enter a sentenc
words = sentence.split() # Splitting the sentence into single words
positions = [words.index(word) + 1 for word in words]
f.write(", ".join(map(str, positions))) # write the places to myFile
myFile.write("\n")
print("The positions are now in the file")
this uses the with statement which handles closing the file for you, behind the scenes.
As I see it, in the for loop, you try to write into file, than close it, and than WRITE TO THE CLOSED FILE again. Couldn't this be the problem?

Checking if a variable contains spaces and letters

I am trying to make a program that asks for a name but will reject the input if it doesn't contain letters/spaces. However, it seems to reject spaces as well as numbers and symbols.
print("Welcome to the Basic Arthmetics Quiz.")
print("What is your name?")
name=input()
if not name.isalpha()or name not in(str(" ")):
print('Please only enter letters for your name!')
while not name.isalpha()or name in(str(" ")):
v=1
print('Please enter your name again.')
name=input()
if name.isalpha()or name not in(str(" ")):
v=0
else:
v=1
Where have I gone wrong?
This looks an awful lot like homework.
Your test name not in(str(" ")), which should be written name not in " ", tests whether name is one of {"", " "}.
It would be easiest to test the name one char at a time, with a per-char condition like
char.isalpha() or char == ' '
Combine this with all and a generator expression to test all chars of name.
The actual implementation, as well as proper code flow (you don't use v, you perform the test thrice, and call input() twice, all of which is unacceptable) are left as exercise.

Using a list of stop-words, and then printing the word that triggered it

I want to search the input for a list of words. So far this works.
swearWords = ["mittens", "boob"]
phrase = raw_input('> ')
listowords = [x.upper() for x in swearWords]
if any(word in phrase.upper() for word in listowords):
print 'Found swear word!'
else:
return
Now let's say I want to print what the word that was found was?
Here is one way to do it (iterate over undesired words, checking whether it's present):
undesired_words = ['blah', 'bleh']
user_input = raw_input('> ')
for word in undesired_words:
if word in user_input.lower():
print 'Found undesired word:', word
print 'User input was OK.'
I've modified your code a bit with some comments, check it out:
swearWords = ["mittens", "boob"]
phrase = raw_input('> ')
# Here I've split the phrase into words so we can iterate through
phrase_words = phrase.split(' ')
# Now we iterate through both the words and the swear words and see if they match
for word in phrase_words:
for swear in swearWords:
if word.upper() == swear.upper():
print "Found swear word:", swear
Here's what I get when I run it:
C:\Users\John\Desktop>temp.py
> These are some swear words. Like boob or mittens maybe. Are those really swear
words?
Found swear word: boob
Found swear word: mittens
Hope this helped!

Resources