通过在字符串中调用写入的 python 函数名称来格式化消息
Format message by calling a written python function name in string
我有功能
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()}")
如果您特别想使用该格式的字符串,还有另一种方法可以实现此目的。但是,上面答案中显示的 fstrings 是一个更好的选择。
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
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']
f-strings 是进行此操作的方法,但这不是问题所在。你可以这样做,但我不建议这样做:
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
我有功能
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()}")
如果您特别想使用该格式的字符串,还有另一种方法可以实现此目的。但是,上面答案中显示的 fstrings 是一个更好的选择。
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
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']
f-strings 是进行此操作的方法,但这不是问题所在。你可以这样做,但我不建议这样做:
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