在 Python 中,您可以在三引号内添加变量吗?如果是这样,如何? [英] In Python, can you have variables within triple quotes? If so, how?

查看:248
本文介绍了在 Python 中,您可以在三引号内添加变量吗?如果是这样,如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于某些人来说,这可能是一个非常简单的问题,但它让我难住了.你能在python的三重引号内使用变量吗?

在下面的例子中,如何在文本中使用变量:

wash_clothes = '星期二'clean_dishes = '从不'mystring =""" 我喜欢在 %wash_clothes 上洗衣服我喜欢洗碗 %clean_dishes"""打印(我的字符串)

我希望结果:

 我喜欢星期二洗衣服我从来不喜欢洗碗

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

解决方案

Python 2 中的方法之一:

<预><代码>>>>mystring =""" 我喜欢在 %s 上洗衣服... 我喜欢洗碗 %s……">>>Wash_clothes = '星期二'>>>clean_dishes = '从不'>>>>>>打印 mystring % (wash_clothes, clean_dishes)我喜欢星期二洗衣服我从来不喜欢洗碗

还要看字符串格式

This is probably a very simple question for some, but it has me stumped. Can you use variables within python's triple-quotes?

In the following example, how do use variables in the text:

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 would like it to result in:

 I like to wash clothes on tuesdays
     I like to clean dishes never

If not what is the best way to handle large chunks of text where you need a couple variables, and there is a ton of text and special characters?

解决方案

One of the ways in 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

Also look at string formatting

这篇关于在 Python 中,您可以在三引号内添加变量吗?如果是这样,如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆