在Python中处理字符串 - 专注于用户输入的部分内容

0 投票
4 回答
1405 浏览
提问于 2025-04-16 01:25
    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."

好的,我知道这段代码不行,我也知道为什么。你不能像对待数字那样去减字符串。

但是有没有办法把一个字符串拆开,只使用其中的一部分呢?我说的“有没有办法”其实是想问“怎么做”,因为在编程中,任何事情都是有可能的。:D

我正在尝试从零开始写我的第一个聊天机器人。

4 个回答

0

这里有一种使用正则表达式的方法:

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
0
# python
  "I like turtles".replace("I like ","")
'turtles'

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

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."

如果你想更深入地了解如何通过灵活的模式来提取字符串中特定的部分,可以看看正则表达式

撰写回答