三重引号内可以有变量吗?如果可以,怎么做?
这可能对一些人来说是个很简单的问题,但我搞不明白。你能在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
如果不能的话,处理那些需要几个变量的大段文本的最佳方法是什么呢?而且这些文本中还有很多特殊字符?
8 个回答
91
没错!从Python 3.6开始,你可以使用f
字符串来实现这个功能:它们会直接在字符串中插入变量的值,所以在执行mystring = ...
这一行后,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)
如果你需要在字符串中添加一个字面上的{
或}
,你只需要把它们写两遍:
if use_squiggly:
kind = 'squiggly'
else:
kind = 'curly'
print(f"""The {kind} brackets are:
- '{{', or the left {kind} bracket
- '}}', or the right {kind} bracket
""")
根据use_squiggly
的值,这段代码会打印出以下内容:
The squiggly brackets are:
- '{', or the left squiggly bracket
- '}', or the right squiggly bracket
或者
The curly brackets are:
- '{', or the left curly bracket
- '}', or the right curly bracket
93
做这件事的推荐方式是使用 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)
73
在Python 2中,有一种方法:
>>> 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
另外,可以看看字符串格式化的内容