'Format message by calling a written python function name in string

I have functions

def getName():
   name = "Mark"
   return name

def getDay():
   day = "Tuesday"
   return day

I have a variable

message = "Hi there [getName] today is [getDay]"

I need to check all occurences for the strings between the square brackets in my message variable and check whether that name is a function that exists so that I can evaluate the value returned by the function and finally come up with a new message string as follows

message = "Hi there Mark, today is Tuesday


Solution 1:[1]

print(f"Hi there {getName()} today is {getDay()}")

Solution 2:[2]

f-strings are the way to go on this but that wasn't the question. You could do it like this but I wouldn't advise it:

import re

def getName():
    return 'Mark'

def getDay():
    return 'Tuesday'

msg = "Hi there [getName] today is [getDay]"

for word in re.findall(r'\[.*?\]', msg):
    try:
        msg = msg.replace(word, globals()[word[1:-1]]())
    except (KeyError, TypeError):
        pass

print(msg)

Output:

Hi there Mark today is Tuesday

Solution 3:[3]

import re

message = "Hi there [getName] today is [getDay]"
b = re.findall(r'\[.*?\]',message)
s=[]
for i in b:
    s.append(i.strip('[]'))
print(s)

Output:

['getName', 'getDay']

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 zeeshan12396
Solution 2
Solution 3 Devang Sanghani