字符串-在Python中,可以在三引号内包含变量吗? 如果是这样,怎么办?
对于某些人来说,这可能是一个非常简单的问题,但这使我感到困惑。 您可以在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
如果不是,在需要几个变量的情况下处理大量文本的最佳方法是什么,并且有大量文本和特殊字符?
XL. asked 2019-12-26T17:11:01Z
7个解决方案
57 votes
执行此操作的首选方法是使用%,而不是使用%:
此字符串格式设置方法是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)
NullUserException answered 2019-12-26T17:11:59Z
48 votes
方法之一:
>>> 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
还要看一下字符串格式
[http://docs.python.org/library/string.html#string-formatting]
pyfunc answered 2019-12-26T17:11:30Z
11 votes
是! 从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)
Antti Haapala answered 2019-12-26T17:12:19Z
8 votes
我认为最简单的方法就是其他人所说的str.format()。
但是,我想我曾提到Python有一个string.Template类,始于Python2.4。
这是文档中的示例。
>>> from string import Template
>>> s = Template('$who likes $what')
>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'
我喜欢这样的原因之一是使用映射而不是位置参数。
chauncey answered 2019-12-26T17:12:53Z
7 votes
是。 我相信这会起作用。
do_stuff = "Tuesday"
mystring = """I like to do stuff on %(tue)s""" % {'tue': do_stuff}
编辑:在格式说明符中忘记了“ s”。
jonesy answered 2019-12-26T17:13:26Z
1 votes
另请注意,您不需要中间变量:
name = "Alain"
print """
Hello %s
""" % (name)
Alain Collins answered 2019-12-26T17:13:46Z
0 votes
以简单的方式传递多个参数
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)
Alkesh Mahajan answered 2019-12-26T17:14:05Z