给定一个带有变量的字符串模式,如何使用 python 匹配和查找变量字符串?

Given a string pattern with a variable, how to match and find variable string using python?

pattern = "world! {} "
text = "hello world! this is python"

根据上面的模式和文本,我如何生成一个将模式作为第一个参数,文本作为第二个参数并输出单词 'this' 的函数?

例如

find_variable(pattern, text) ==> returns '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.

Code Demo

不是像 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))