繁体   English   中英

如何在不打印的情况下保持字符串的打印格式?

[英]How do you keep print formatting of a string without printing?

我有一个用 print 完美格式化的变量,但没有它看起来很糟糕。 我试图将它作为电子邮件的正文传递给一个函数,以便 python 发送,但它的格式不正确。 是否有一个函数可以让它在字符串中看到 /n 等并将其转换为另一个字符串?

发送电子邮件的功能是:

def send_mail(from_email, email_group, subject_text, body_text, attachment=None):
    """
    Function to send emails.
    Inputs:
        - email_group: comma separated string of emails to send message to; str
        - attachment: Location of attachment to send; str
        - subject_text: Subject of the email; str
        - body_text: Body of the email; str
    """
    if attachment == None:
        email = Email(
            to_email=email_group,
            from_email=from_email,
            body=body_text,
            email_type='html',
            subject=subject_text)
    else:
        email = Email(
            to_email=email_group,
            from_email=from_email,
            body=body_text,
            email_type='html',
            subject=subject_text,
            attach=[attachment])
    email.send()

不打印:

System Status Update Complete Min Date: 2022-07-17 Max Date: 2022-07-17 Summary: var1 var2 var3 var4 var5 count 1905.000000 1905.000000 1905.000000 1905.000000 1905.000000

带打印:

System Status Update Complete
Min Date: 2022-07-17
Max Date: 2022-07-17
Summary:
              var1         var2         var3          var4          var5
count  1905.000000  1905.000000  1905.000000   1905.000000   1905.000000

正如@TimRoberts 在评论中建议的那样,在<pre>之前和</pre>之后添加它的格式确实正确。

我忘记了传递的字符串被解释为 HTML。 希望这个答案可以在将来为某人节省一些精力。

def send_mail(from_email, email_group, subject_text, body_text, attachment=None):
    """
    Function to send emails.
    Inputs:
        - email_group: comma separated string of emails to send message to; str
        - attachment: Location of attachment to send; str
        - subject_text: Subject of the email; str
        - body_text: Body of the email; str
    """
    if attachment == None:
        email = Email(
            to_email=email_group,
            from_email=from_email,
            body='<pre>'+body_text+'</pre>',
            email_type='html',
            subject=subject_text)
    else:
        email = Email(
            to_email=email_group,
            from_email=from_email,
            body='<pre>'+body_text+'</pre>',
            email_type='html',
            subject=subject_text,
            attach=[attachment])
    email.send()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM