Reputation: 163
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
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
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
.
Upvotes: 1