gpt4 book ai didi

python - 三引号内可以有变量吗?如果是这样,怎么做?

转载 作者:IT老高 更新时间:2023-10-28 20:28:57 25 4
gpt4 key购买 nike

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

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

最佳答案

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

This method of string formatting is the new standard in Python 3.0, and should be preferred to the % formatting described in String Formatting Operations in new code.

例子:

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)

关于python - 三引号内可以有变量吗?如果是这样,怎么做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3877623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com