【问题标题】:Python: Use Variable in mulit-line stringPython:在多行字符串中使用变量
【发布时间】:2020-10-08 16:13:33
【问题描述】:

我有两个变量:

subject = 'this is the subject'
body = 'this is the content'

为了使用 smtplib 发送每封电子邮件,我将我的消息变量作为多行字符串。但是 .format() 方法不起作用。有没有人想办法解决这个问题?

消息字符串:

    message = """\
    Subject: (variable subject)


    (variable content)"""

【问题讨论】:

  • “但是 .format() 方法不起作用。”是的,它确实。你到底尝试了什么?请始终包含minimal reproducible example
  • (variable subject) 不是 str.format 的正确格式

标签: python string smtplib multilinestring


【解决方案1】:

为简单起见,您可以使用 f 字符串:

message = f"""
    Subject: {subject}


    {body}"""

这是使用format()的正确方法:

message = """
subject = {}


{}
""".format(subject, body)

要使用格式,请将 {} 放置在需要添加变量的位置,然后使用 sequential 您想要的变量列表声明 .format() @987654326 @被替换为

【讨论】:

  • @juanpa.arrivillaga 确实如此,但我认为这对初学者更友好,而且使用起来更容易:^)
  • 你能在底部添加它作为python
  • IMO .format 更加冗长和直接;初学者更容易掌握它的概念。不过f-strings 肯定更容易使用。
【解决方案2】:

试试这个:

>>> subject = 'this is the subject'
>>> body = 'this is the content'
>>> message = '''\
... Subject: {subject}
...
... {body}\
... '''.format(subject=subject, body=body)
>>> print(message)
Subject: this is the subject
this is the content

【讨论】:

    【解决方案3】:

    @juanpa.arrivillaga

    我的尝试:

    message = """\
        Subject: {.format(subject)}
    
    
        Python test"""
    

    【讨论】:

    • 看看我下面的答案,看看正确的使用方法,它实际上要简单得多!
    【解决方案4】:

    我不完全确定你指的是什么,但这是我的最佳猜测:

    message = 'Subject: {}\n\n{}'.format(subject,body)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 2021-10-24
      • 1970-01-01
      • 2015-04-02
      • 2012-04-24
      • 2021-11-03
      • 1970-01-01
      相关资源
      最近更新 更多