如何将print函数()的结果存储到变量中,以将其包含在f字符串中



我有以下数据帧:

data={'Process_ID':['12345-98', '23547-75', '85763-99','44231-56','78456-00','53218-87'],
'Date': ['2021-06-30','2022-08-10','2021-06-15','2023-10-02','2024-04-03','2021-06-25'],
'Check': ['True','False','False','True','True','False']}
df=pd.DataFrame(data)
print(df)

输出如下:

Process_ID        Date  Check
0   12345-98  2021-06-30   True
1   23547-75  2022-08-10  False
2   85763-99  2021-06-15  False
3   44231-56  2023-10-02   True
4   78456-00  2024-04-03   True
5   53218-87  2021-06-25  False

我想只为check="的行选择进程ID和截止日期;真";,所以我做了这个:

def printfunc():
df['Check']=pd.eval(df['Check'].astype(str).str.title())
out=df.loc[df['Check'],['Process_ID','Date']].T
for x in out:
print('Process ID:',out[x].values[0],'nDue Date:',out[x].values[1],'n')
content=printfunc()
content

输出:

Process ID: 12345-98 
Due Date: 2021-06-30 
Process ID: 44231-56 
Due Date: 2023-10-02 
Process ID: 78456-00 
Due Date: 2024-04-03

现在,我想在f字符串中包含"内容变量",因为我将自动发送电子邮件来显示这些信息。然而,当我尝试这样做时,它会返回一个"无"值:

email_text=f"""
Dear,
The due dates for the processes are the following:
{content}
Thank you.
Best Regards,
"""
print(email_text)

输出:

Dear,
The due dates for the processes are the following:
None
Thank you.
Best Regards,

如何将此变量包含在f字符串中以进行打印?

尝试:

def printfunc():
s=''
df['Check']=pd.eval(df['Check'].astype(str).str.title())
out=df.loc[df['Check'],['Process_ID','Date']].T
for x in out:
s+='Process ID:'+out[x].values[0]+'nDue Date: '+out[x].values[1]+'nn'
return s
content=printfunc()

最后:

email_text=f"""
Dear,
The due dates for the processes are the following:
{content}
Thank you.
Best Regards,
"""
print(email_text)

解释:

这个函数只是打印值,它不会返回任何东西,所以这就是你得到'None'的原因

因此,我们创建了一个变量s,并将空字符''分配给它,然后在函数的for循环中添加字符串并将其分配回它

附言:抱歉解释不正确。。。我不善于解释:(

print(df)只是将str(df)返回的内容写入标准输出。

最新更新