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

How to store the result of a print function () into a variable to include it in a f string

我有以下数据框:

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

我想 select 仅针对 check="True" 的行的进程 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 字符串中包含 'content variable',因为我会自动发送电子邮件来显示此信息。但是,当我尝试这样做时,它 returns 一个 'None' 值:

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 字符串中以便能够打印它?

print(df) 只是写入标准输出 str(df) returns.

尝试:

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]+'\n\n'
    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 循环中添加字符串并将其赋值回它

P.S: 抱歉解释不好...我不擅长解释事情 :(