Suppose I have a large chunk of text, say
The third and final rotation of Himalayan Pilgrimage explores the theme of Sacred Space with a pair of magnificent large mandala paintings, two-dimensional representations of a three-dimensional architectural space where a specific deity resides. Dating to the fourteenth and sixteenth centuries, these paintings represent, in vivid colors, a cosmology of the deity Hevajra. Several other paintings on view depict historic teachers of various Tibetan orders.
In Java I can write it as
"The third and final rotation of Himalayan Pilgrimage explores "
+ "the theme of Sacred Space with a pair of magnificent large "
+ "mandala paintings, two-dimensional representations of a "
+ "three-dimensional architectural space where a specific "
+ "deity resides. Dating to the fourteenth and sixteenth "
+ "centuries, these paintings represent, in vivid colors, "
+ "a cosmology of the deity Hevajra. Several other paintings"
+ " on view depict historic teachers of various Tibetan orders."
In Python, however, if I do the same, I get complaints about the plus signs +
. If instead I use '''
I get a bunch of leading white spaces due to indentation (indentation so the code is easy to read).
Does anyone know the solution to this problem: how to paste a big chuck of text into Python code without incurring white spaces?
The answer I am looking for is not: put the whole text on one line
Again, I need to add text that span more than one line without incurring additional white space.
When you use the triple quote string you do not have to indent:
class SomeClass(object):
def somemethod(self):
return '''\
This text
does not need to be indented
at all.
In this text, newlines are preserved.
'''
# but do continue the next line at the right indentation.
You can also join strings automatically by using parenthesis:
foo = (
"this text will be "
"joined into one long string. "
"Note that I don't need to concatenate these "
"explictly. No newlines are included\n"
"unless you insert them explicitly."
)
because python will concatenate consecutive strings in one expression together automatically (see String literal concatenation).
You are still free to use +
signs to concatenate the strings explicitly, but do use parenthesis to make it one expression:
foo = (
"this text will be " +
"joined into one long string. " +
"It is concatenated " +
"explictly using the `+` operator."
)
The alternative would be to use a backslash before the end of the line:
foo = "This is not " \
"recommended"
but I find using parentheses and string literal concatenation to be more readable.
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