在python中操作字符串 - 专注于用户输入的一部分

Teh*_*hto 0 python

    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."
Run Code Online (Sandbox Code Playgroud)

好的,我知道这段代码不起作用,我知道为什么.您不能像数字一样相互减去字符串.

但有没有办法打破一个字符串,只使用部分响应?并且通过"有一种方式"我的意思是"如何",因为在编程中一切皆有可能.:d

我正试图从头开始编写我的第一个聊天机器人.

Amb*_*ber 5

一种选择是简单地用空字符串替换要删除的部分:

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."
Run Code Online (Sandbox Code Playgroud)

如果要查看更高级的模式匹配以通过灵活模式获取字符串的更多特定部分,您可能需要查看正则表达式.