这对某些人来说可能是一个非常简单的问题,但它让我很难过。你能在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)
我希望它导致:
I like to wash clothes on tuesdays
I like to clean dishes never
如果不是什么是处理大块文本的最佳方法,你需要一些变量,并且有大量的文字和特殊字符?
其中一种方式:
>>> 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
另请查看字符串格式
这样做的首选方法是使用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)
我认为最简单的方法是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'
我喜欢这个的原因之一是使用映射而不是位置参数。
是。我相信这会奏效。
do_stuff = "Tuesday"
mystring = """I like to do stuff on %(tue)s""" % {'tue': do_stuff}
编辑:忘记了格式说明符中的's'。
是!从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)
另请注意,您不需要中间变量:
name = "Alain"
print """
Hello %s
""" % (name)
以简单的方式传递多个args
wash_clothes = 'tuesdays'
clean_dishes = 'never'
a=""" I like to wash clothes on %s I like to clean dishes %s"""%(wash_clothes,clean_dishes)
print(a)