Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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]"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

There is another way of achieving this if you specifically want to use the string in that format. However, fstrings as shown in the above answer are a much superior alternative.

def f(message):
    returned_value=''
    m_copy=message
    while True:
        if '[' in m_copy:
            returned_value+=m_copy[:m_copy.index('[')]
            returned_value+=globals()[m_copy[m_copy.index('[')+1:m_copy.index(']')]]()
            m_copy=m_copy[m_copy.index(']')+1:]
        else:
            return returned_value+m_copy
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading