0

Below I have some code for a system that looks for keywords in sentences, I'm using the .split() extension for this task. It works fine but when I input the same keyword for example, "Hello." the full stop in my input doesn't match the codes so it returns an error. My question is that is there a way to allow grammatical inputs such as .Upper() and .Lower() allow for capital letters etc?

input1 = input("Input 'Hello'")
response = input1.split()

if "Hello" in response:
   print("Howdy!")

Output Error:

"Hello." is not defined.
Tonechas
  • 11,520
  • 14
  • 37
  • 68
  • You could `.strip()` non-letters, or use regular expressions. – Jasper Dec 08 '16 at 16:22
  • Thanks, where would it go in my code? – Josh Brown Dec 08 '16 at 16:24
  • 1
    This isn't the right place to explain regular expressions, for `.strip()`: `input1.strip('.!?')` will remove full stops, exclamation and question marks at the start and end of `input1`. – Jasper Dec 08 '16 at 16:38
  • Oh I need something that still allows the "Howdy" to print even if the person inputs "Hello!!!!" **An input with grammatical characters in** – Josh Brown Dec 08 '16 at 16:40

2 Answers2

3

You don't need to use split particularly - the in operator will check if one string is a substring of another. You could use the following:

input1 = input("Input 'Hello'").lower()

if "hello" in input1:
   print("Howdy!")

Which will return a message any time hello is included in the user's input, regardless of case or punctuation.

asongtoruin
  • 8,389
  • 2
  • 27
  • 38
0

If you want to do this using regular expressions, you can do something like:

import re
input1 = input("Input 'Hello'").lower() # from asongtoruin's answer
input1 = re.sub(r'[^\w]', '', input1) # replace everything not a word character with empty string

if input1 == "hello":
   print("Howdy!")

Which first filters out everything not a word, and then compares.

But like Jasper mentioned, it would be simpler to use .strip() if you know what the user will enter (although that wouldn't cover periods, etc. in the middle of the word)

input1 = input("Input 'Hello'").lower() # from asongtoruin's answer
input1 = input1.strip('.!?') # or try: strip(string.punctuation)

if input1 == "hello":
   print("Howdy!")

See Best way to strip punctuation from a string in Python for further information..

Community
  • 1
  • 1
Matthias
  • 1,887
  • 1
  • 18
  • 35