加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

有没有办法在Python中的多行字符串中使用变量?

发布时间:2020-12-20 11:50:16 所属栏目:Python 来源:网络整理
导读:参见英文答案 String formatting in Python????????????????????????????????????9个 所以我将此作为邮件发送脚本的一部分: try: content = ("""From: Fromname fromemail To: Toname toemail MIME-Version: 1.0 Content-type: text/html Subject: test Thi
参见英文答案 > String formatting in Python????????????????????????????????????9个
所以我将此作为邮件发送脚本的一部分:

try:
    content = ("""From: Fromname <fromemail>
    To: Toname <toemail>
    MIME-Version: 1.0
    Content-type: text/html
    Subject: test

    This is an e-mail message to be sent in HTML format

    <b>This is HTML message.</b>
    <h1>This is headline.</h1>
    """)

mail.sendmail('from','to',content)

我想每次使用不同的主题(让我们说它是函数参数).

我知道有几种方法可以做到这一点.

但是,我也使用ProbLog来处理我的一些其他脚本(一种基于Prolog语法的概率编程语言).
据我所知,在Python中使用ProbLog的唯一方法是通过字符串,如果字符串在几个部分中断了; example =(“”“string”“”,variable,“”“string2”“”),以及上面的电子邮件示例中,我无法使其工作.

我实际上有一些脚本,在多行字符串中使用变量可能很有用,但你明白了.

有没有办法让这项工作?
提前致谢!

解决方法

使用.format方法:

content = """From: Fromname <fromemail>
    To: {toname} <{toemail}>
    MIME-Version: 1.0
    Content-type: text/html
    Subject: {subject}

    This is an e-mail message to be sent in HTML format

    <b>This is HTML message.</b>
    <h1>This is headline.</h1>
"""
mail.sendmail('from',content.format(toname="Peter",toemail="p@tr",subject="Hi"))

一旦最后一行变得太长,您可以改为创建一个字典并将其解压缩:

peter_mail = {
    "toname": "Peter","toemail": "p@tr","subject": "Hi",}
mail.sendmail('from',content.format(**peter_mail))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读