String Concatenation:在Python代码中放入大量文本

lea*_*ner 5 python string python-2.7

假设我有一大块文字

喜马拉雅朝圣的第三次也是最后一次旋转探索了神圣空间的主题,其中有一对华丽的大型曼荼罗绘画,是一个三维建筑空间的二维表现,一个特定的神灵所在.这些绘画的历史可以追溯到十四世纪和十六世纪,以生动的色彩代表着神灵Hevajra的宇宙观.其他几幅画作描绘了各种西藏秩序的历史教师.

在Java中我可以把它写成

"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."
Run Code Online (Sandbox Code Playgroud)

但是,在Python中,如果我这样做,我会收到有关加号的投诉+.如果相反,我使用'''由于缩进而得到一堆前导空格(缩进,因此代码易于阅读).

有没有人知道这个问题的解决方案:如何在不产生空格的情况下将大量文本粘贴到Python代码中?

我正在寻找的答案不是:将整个文本放在一行

同样,我需要添加跨越多行的文本,而不会产生额外的空白.

Mar*_*ers 14

当您使用三重引号字符串你不具备缩进:

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.
Run Code Online (Sandbox Code Playgroud)

您还可以使用括号自动连接字符串:

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."
)
Run Code Online (Sandbox Code Playgroud)

因为python会自动将一个表达式中的连续字符串连接在一起(参见String literal concatenation).

你仍然可以自由地使用+符号来明确地连接字符串,但是使用括号使它成为一个表达式:

foo = (
    "this text will be " +
    "joined into one long string. " + 
    "It is concatenated " +
    "explictly using the `+` operator."
)
Run Code Online (Sandbox Code Playgroud)

另一种方法是在行尾之前使用反斜杠:

foo = "This is not " \
    "recommended"
Run Code Online (Sandbox Code Playgroud)

但我发现使用括号和字符串文字串联更具可读性.