三引号内可以有变量吗?如果是的话,怎么办?

问题描述 投票:0回答:8

对于某些人来说,这可能是一个非常简单的问题,但它却难倒了我。你能在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

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

python string formatting
8个回答
93
投票

执行此操作的首选方法是使用 f-strings (在 3.6 中引入)而不是

str.format()
或使用
%
:

示例:

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)

Python 2 中的标准(此时你绝对不应该继续使用它——自 2020 年以来就不再支持它),是

str.format()


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

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

另请注意字符串格式


12
投票

是的。我相信这会起作用。

do_stuff = "Tuesday"

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

编辑:忘记格式说明符中的“s”。


10
投票

我认为最简单的方法是 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'

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


2
投票

另请注意,您不需要中间变量:

name = "Alain"
print """
Hello %s
""" % (name)

0
投票

以简单的方式传递多个参数

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)

0
投票

这是我项目中的真实工作代码。使用 3 个单引号。请注意使用带有 %s 的单引号。

day = "2023-07-11"

df_t= spark.sql('''
    select * from db.article_events_ where yyyy_mm_dd < '%s'
    ''' %(day))
df_t.count()
© www.soinside.com 2019 - 2024. All rights reserved.