Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 639
XL. Avatar asked Oct 06 '10 23:10

XL.


People also ask

How do you pass a variable in triple quotes in Python?

We can use the \ (backslash) to break strings up into multiple lines in the source code. Special characters not inside triple quote strings must be escaped with a \ (backslash). Don't use %-formatting to format strings. Use the .

Can strings be enclosed in triple quotes?

A string literal can span multiple lines, but there must be a backslash \ at the end of each line to escape the newline. String literals inside triple quotes, """ or ''', can span multiple lines of text.

Can triple quoted strings span multiple lines :?

Spanning strings over multiple lines can be done using python's triple quotes. It can also be used for long comments in code.

Which data can be enclosed with single or double or triple quotes?

In Python, a string ( str ) is created by enclosing text in single quotes ' , double quotes " , and triple quotes ( ''' , """ ). It is also possible to convert objects of other types to strings with str() . This article describes the following contents.


2 Answers

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) 
like image 94
NullUserException Avatar answered Oct 02 '22 19:10

NullUserException


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

  • http://docs.python.org/library/string.html#string-formatting
like image 38
pyfunc Avatar answered Oct 02 '22 18:10

pyfunc