我有功能
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
uj5u.com熱心網友回復:
print(f"Hi there {getName()} today is {getDay()}")
uj5u.com熱心網友回復:
如果您特別想使用該格式的字串,還有另一種方法可以實作此目的。但是,上述答案中顯示的 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
uj5u.com熱心網友回復:
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
uj5u.com熱心網友回復:
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']
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/432887.html
標籤:Python python-3.x 功能 python-2.7 评估
上一篇:在python中用空格替換下劃線
下一篇:將列均值作為函式的一部分
