1

So basically I want a program that will only work if the user types something like "I am sick" or "I am too cool" but will not work if they make a typo like "pi am cool".

Here's what I have so far:

text = input("text here: ") 
if re.search("i am", text) is not None:
   print("correct")

So basically, I just need help with if someone types in "Pi am cool" right now it will think that is correct. However I do not want that, I want it so that it has to be exactly "i am cool" however. Since I am creating a ai bot for a school project I need it so the sentence could be "man, I am so cool" and it will pick it up and print back correct, but if it was typed "Man, TI am so cool" with a typo I don't want it to print out correct.

1
  • 1
    Can you post more specific requirements? You've given a few inputs your code should or shouldn't accept, but it'd be easier to answer if we had an actual description of what should be accepted instead of just examples. Commented Sep 6, 2013 at 6:44

1 Answer 1

2

Use \b word boundary anchors:

if re.search(r"\bi am\b", text) is not None:

\b matches points in the text that go from a non-word character to a word character, and vice-versa, so space followed by a letter, or a letter followed by a word.

Because \b in a regular python string is interpreted as a backspace character, you need to either use a raw string literal (r'...') or escape the backslash ("\\bi am\\b").

You may also want to add the re.IGNORE flag to your search to find both lower and uppercase text:

if re.search(r"\bi am\b", text, re.IGNORE) is not None:

Demo:

>>> re.search(r"\bi am\b", 'I am so cool!', re.I).group()
'I am'
>>> re.search(r"\bi am\b", 'WII am so cool!', re.I) is None
True
>>> re.search(r"\bi am\b", 'I ammity so cool!', re.I) is None
True
Sign up to request clarification or add additional context in comments.

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.