解決方案:
def replace_new(s):
# 讀取出來的數據用context的數據去替換,loan_id 動態替換
p = '\$\{(.*?)}'
while re.search(p, s):
m = re.search(p, s)
key = m.group(1)
if hasattr(Context, key):
value = str(getattr(Context, key)) #重點: 取出來的是int類型,所以應該轉換成字符串去替換
s = re.sub(p, value, s, count=1)
else:
return None
return s
s = '{"mobilephone": "${borrow_user}", "pwd": "${borrow_pwd}"}'
s = replace_new(s)
print(s)