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?
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 .
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.
Spanning strings over multiple lines can be done using python's triple quotes. It can also be used for long comments in code.
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.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With