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

2024-03-29 13:20:52 发布

您现在位置:Python中文网/ 问答频道 /正文

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

给定上面的模式和文本,如何生成一个函数,将模式作为第一个参数,文本作为第二个参数,并输出单词this?你知道吗

例如

find_variable(pattern, text)==>;返回'this',因为'this'


Tags: 函数text文本gthelloworld参数is
2条回答

不是像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构建包含单个捕获组的正则表达式:

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

相关问题 更多 >