105

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?

codeforester
  • 39,467
  • 16
  • 112
  • 140
XL.
  • 1,390
  • 4
  • 11
  • 13

8 Answers8

90

The preferred way of doing this is using str.format() rather than the method using %:

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.

Example:

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)
NullUserException
  • 83,810
  • 28
  • 209
  • 234
83

Yes! Starting from Python 3.6 you can use the f strings for this: They're interpolated in place, so mystring would have the desired value after the mystring = ... line:

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)

Should you need to add a literal { or } in the string, you would just double it:

if use_squiggly:
    kind = 'squiggly'
else:
    kind = 'curly'

print(f"""The {kind} brackets are:
  - '{{', or the left {kind} bracket
  - '}}', or the right {kind} bracket
""")

would print, depending on the value of use_squiggly, either

The squiggly brackets are:
  - '{', or the left squiggly bracket
  - '}', or the right squiggly bracket

or

The curly brackets are:
  - '{', or the left curly bracket
  - '}', or the right curly bracket
74

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

Ian Smith
  • 879
  • 1
  • 12
  • 23
pyfunc
  • 65,343
  • 15
  • 148
  • 136
  • That is perfect. Thanks so much! That is exactly what I was looking for! I don't exactly get how python knows which %s to replace with which variable, though. Does it look at the order the variables appear in the following: print mystring % (wash_clothes, clean_dishes) – XL. Oct 06 '10 at 23:36
  • @XL : You can take a look at the other formatting technique for which I had provided the link but the example. The example was provided by NullUserException. You can use both the techniques. – pyfunc Oct 06 '10 at 23:38
12

Yes. I believe this will work.

do_stuff = "Tuesday"

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

EDIT: forgot an 's' in the format specifier.

jonesy
  • 3,502
  • 17
  • 23
10

I think the simplest way is str.format() as others have said.

However, I thought I'd mention that Python has a string.Template class starting in Python2.4.

Here's an example from the docs.

>>> from string import Template
>>> s = Template('$who likes $what')
>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'

One of the reasons I like this is the use of a mapping instead of positional arguments.

chauncey
  • 676
  • 11
  • 20
  • That is an interesting approach. I really don't like the positional arguments either as it may become tricky if you have a really large number of variables. The only question that I have is whether this method is worthwhile if you have massive amounts of formatted text and special characters in the template string? – XL. Oct 07 '10 at 00:13
  • 2
    you can use positional arguments with `format`. `d = dict(foo=1, bar=2); "{foo} {bar}".format(**d)` – aaronasterling Oct 07 '10 at 02:55
  • `string.Template` is orders of magnitude slower than other methods – ccpizza Jul 03 '18 at 08:51
2

Also note that you don't need the intermediate variable:

name = "Alain"
print """
Hello %s
""" % (name)
Alain Collins
  • 16,268
  • 2
  • 32
  • 55
0

Pass multiple args in simple way

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)
Alkesh Mahajan
  • 469
  • 6
  • 17
0

This is real working code from my project. Uses 3 single quotes. note the use of single quotes with %s.

day = "2023-07-11"

df_t= spark.sql('''
    select * from db.article_events_ where yyyy_mm_dd < '%s'
    ''' %(day))
df_t.count()
Blue Clouds
  • 7,295
  • 4
  • 71
  • 112