在Python中,你可以在三引号中包含变量吗?如果是这样,怎么样?

XL.*_*XL. 55 python string

这对某些人来说可能是一个非常简单的问题,但它让我很难过.你能在python的三引号中使用变量吗?

在以下示例中,如何在文本中使用变量:

wash_clothes = 'tuesdays'
clean_dishes = 'never'

mystring =""" I like to wash clothes on %wash_clothes
I like to clean dishes %clean_dishes
"""

print(mystring)
Run Code Online (Sandbox Code Playgroud)

我希望它导致:

 I like to wash clothes on tuesdays
     I like to clean dishes never
Run Code Online (Sandbox Code Playgroud)

如果不是什么是处理大块文本的最佳方法,你需要一些变量,并且有大量的文字和特殊字符?

Nul*_*ion 57

这样做的首选方法是使用str.format()而不是使用%以下方法:

这种字符串格式化方法是Python 3.0中的新标准,应该优先%于新代码中字符串格式化操作中描述的格式.

例:

wash_clothes = 'tuesdays'
clean_dishes = 'never'

mystring =""" I like to wash clothes on {0}
I like to clean dishes {1}
"""

print mystring.format(wash_clothes, clean_dishes)
Run Code Online (Sandbox Code Playgroud)

  • 而 const 字符串 `{`、`}` 可以转义为 `{{`、`}}`。 (7认同)

pyf*_*unc 49

其中一种方式:

>>> mystring =""" I like to wash clothes on %s
... I like to clean dishes %s
... """
>>> wash_clothes = 'tuesdays'
>>> clean_dishes = 'never'
>>> 
>>> print mystring % (wash_clothes, clean_dishes)
 I like to wash clothes on tuesdays
I like to clean dishes never
Run Code Online (Sandbox Code Playgroud)

另请查看字符串格式


Ant*_*ala 14

是! 从Python 3.6开始,您可以使用以下f字符串:它们是在适当位置插值的,因此mystring已经是必需的输出。

wash_clothes = 'tuesdays'
clean_dishes = 'never'

mystring = f"""I like to wash clothes on {wash_clothes}
I like to clean dishes {clean_dishes}
"""

print(mystring)
Run Code Online (Sandbox Code Playgroud)

  • @哪里没有!一点也不。 (2认同)

小智 8

我认为最简单的方法是str.format(),正如其他人所说的那样.

但是,我想我会提到Python有一个从Python2.4开始的string.Template类.

这是文档中的一个示例.

>>> from string import Template
>>> s = Template('$who likes $what')
>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'
Run Code Online (Sandbox Code Playgroud)

我喜欢这个的原因之一是使用映射而不是位置参数.

  • 你可以使用`format`的位置参数.`d = dict(foo = 1,bar = 2); "{foo} {bar}".format(**d)` (2认同)

jon*_*esy 7

是.我相信这会奏效.

do_stuff = "Tuesday"

mystring = """I like to do stuff on %(tue)s""" % {'tue': do_stuff}

编辑:忘记了格式说明符中的's'.

  • 如果你要记下答案,请说明原因,以便我们都可以从错误中吸取教训. (3认同)
  • 这对于重复变量非常有用 (2认同)