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

0

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

If I use the pattern = "${} off" with text = "$10 off" it isn't able to find the 10. Any ideas?
Change return line to this: return re.findall(re.escape(pattern).replace(r'\{\}', r'(\S+)'), text)[0]
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.