通过调用字符串中编写的python函数名来格式化消息



我有函数

def getName():
name = "Mark"
return name
def getDay():
day = "Tuesday"
return day

我有一个可变

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

我需要检查message变量中方括号之间字符串的所有出现情况,并检查该名称是否是一个存在的函数,以便我可以评估该函数返回的值,并最终得出如下所示的新消息字符串

message = "Hi there Mark, today is Tuesday
print(f"Hi there {getName()} today is {getDay()}")

如果您特别想使用这种格式的字符串,还有另一种方法可以实现这一点。然而,上面的答案中显示的fstring是一个更好的选择。

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

f-string是实现这一点的方法,但这不是问题所在。你可以这样做,但我不建议:

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)

输出:

Hi there Mark today is Tuesday
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)

输出:

['getName', 'getDay']

相关内容

  • 没有找到相关文章

最新更新