Why is this variable not being evaluated?

Question:

I want to create a python function that receives 2 strings, I want to search the first within the second.

#Function to evaluate a string in a multiline string
def checkString(mystring, maintext):
    result = re.findall(r'^mystring', maintext, re.MULTILINE)
    if len(result) == 0:
        return False
    else:
        return True

My variable "mystring" is not being evaluated, I always get False. I know the re.findall works because if I take out of the function, it works, so I am evaluating this wrong.

Asked By: darko

||

Answers:

you need to template the variable mystring in your regexp: substitute

    result = re.findall(r'^mystring', maintext, re.MULTILINE)

with an f-string:

    result = re.findall(rf'^{mystring}', maintext, re.MULTILINE)
Answered By: Alberto Garcia
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.