2024-03-29 13:20:52 发布
网友
pattern = "world! {} " text = "hello world! this is python"
给定上面的模式和文本,如何生成一个函数,将模式作为第一个参数,文本作为第二个参数,并输出单词this?你知道吗
例如
find_variable(pattern, text)==>;返回'this',因为'this'
find_variable(pattern, text)
不是像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))
您可以使用此函数来使用string.format构建包含单个捕获组的正则表达式:
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。你知道吗
findall
Code Demo
不是像anubhava那样的一行代码,而是使用基本的python知识:
您可以使用此函数来使用
string.format
构建包含单个捕获组的正则表达式:PS:您可能需要在函数中添加一些健全性检查,以验证字符串格式和成功的
findall
。你知道吗Code Demo
相关问题 更多 >
编程相关推荐