Skip to content
Advertisement

Can you have variables within triple quotes? If so, how?

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?

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement