0

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
  • Just FYI, doing something like this in actual code is likely to be a security risk. I'll post an answer shortly. – Mous Feb 25 '22 at 11:07
  • You can call the variables and if they are not functions, they will return with error. – Devang Sanghani Feb 25 '22 at 11:07
  • https://stackoverflow.com/questions/2459329/how-to-determine-if-the-variable-is-a-function-in-python?lq=1 – Devang Sanghani Feb 25 '22 at 11:11
  • @Mous thank you I will be waiting. Most likely the original ```message``` variable will be called from a database record. And if this way poses a security risk. How else would you go about to solve such a problem? – thisissifumwike Feb 25 '22 at 11:16
  • 1
    [How do I ask and answer homework questions?](https://meta.stackoverflow.com/q/334822) – 0stone0 Feb 25 '22 at 11:18

4 Answers4

2
print(f"Hi there {getName()} today is {getDay()}")
zeeshan12396
  • 382
  • 1
  • 8
1

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
Mous
  • 953
  • 3
  • 14
1

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
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
0
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']
Devang Sanghani
  • 731
  • 5
  • 14