pattern = "world! {} "
text = "hello world! this is python"
鉴于上面的模式和文本,我如何生成一个函数,它将pattern作为第一个参数,text作为第二个参数并输出单词'this'?
例如。
find_variable(pattern, text)
==>返回'this'因为'this'
您可以使用此函数使用string.format
构建具有单个捕获组的正则表达式:
>>> pattern = "world! {} "
>>> text = "hello world! this is python"
>>> def find_variable(pattern, text):
... return re.findall(pattern.format(r'(\S+)'), text)[0]
...
>>> print (find_variable(pattern, text))
this
PS:你可能想在你的函数中添加一些健全性检查来验证字符串格式和成功的findall
。
不是像anubhava那样的一个班轮,而是使用基本的python知识:
pattern="world!"
text="hello world! this is python"
def find_variabel(pattern,text):
new_text=text.split(' ')
for x in range(len(new_text)):
if new_text[x]==pattern:
return new_text[x+1]
print (find_variabel(pattern,text))