Denny
Denny

Reputation: 163

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

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

Given the pattern and text above, how do I produce a function that would take pattern as the first argument and text as the second argument and output the word 'this'?

eg.

find_variable(pattern, text) ==> returns 'this' because 'this'

Upvotes: 0

Views: 530

Answers (2)

Abhinay Pandey
Abhinay Pandey

Reputation: 64

Not a one liner like anubhava's but using basic python knowledge:

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

Upvotes: 0

anubhava
anubhava

Reputation: 784998

You may use this function that uses string.format to build a regex with a single captured group:

>>> 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: You may want to add some sanity checks inside your function to validate string format and a successful findall.

Code Demo

Upvotes: 1

Related Questions