Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Concatenation: Putting large chuck of text in Python code

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.

like image 682
learner Avatar asked Jan 29 '13 17:01

learner


1 Answers

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.

like image 130
Martijn Pieters Avatar answered Sep 30 '22 13:09

Martijn Pieters