tags:

views:

44

answers:

4
    resp = raw_input("What is your favorite fruit?\n")
if "I like" in resp:
    print "%s" - "I like" + " is a delicious fruit." % resp
else:
    print  "Bubbles and beans."

OK I know this code doesn't work, and I know why. You can't subtract strings from each other like numbers.

But is there a way to break apart a string and only use part of the response? And by "is there a way" I really mean "how," because anything is possible in programming. :D

I'm trying to write my first chatterbot from scratch.

+5  A: 

One option would be to simply replace the part that you want to remove with an empty string:

resp = raw_input("What is your favorite fruit?\n")
if "I like" in resp:
    print "%s is a delicious fruit." % (resp.replace("I like ", ""))
else:
    print  "Bubbles and beans."

If you want to look into more advanced pattern matching to grab out more specific parts of strings via flexible patterns, you might want to look into regular expressions.

Amber
Also string.split() for some cases.
Nicholas Knight
A: 
# python
  "I like turtles".replace("I like ","")
'turtles'
eruciform
A: 

Can you just strip "I like"?

resp.strip("I like")

be careful of case sensitivity though.

Barrest
strip() doesn't do what you think it does. "I like apple".strip("I like") becomes "app".
Ned Batchelder
A: 

Here's a way to do it with regular expressions:

In [1]: import re

In [2]: pat = r'(I like )*(\w+)( is a delicious fruit)*'

In [3]: print re.match(pat, 'I like apples').groups()[1]
apples

In [4]: print re.match(pat, 'apple is a delicious fruit').groups()[1]
apple
ars