python - 字符串连接 : Putting large chuck of text in Python code

标签 python string python-2.7

假设我有一大段文字,比如说

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.

在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."

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

有谁知道这个问题的解决方案:如何将一大段文本粘贴到 Python 代码中而不产生空格?

我要找的答案不是:把整个文本放在一行

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

最佳答案

当您使用三重引号字符串时,您必须缩进:

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.

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

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."
)

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

您仍然可以自由地使用 + 符号来显式连接字符串,但请使用括号使其成为一个表达式:

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

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

foo = "This is not " \
    "recommended"

但我发现使用括号和字符串文字连接更具可读性。

关于python - 字符串连接 : Putting large chuck of text in Python code,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14588851/

相关文章:

python - 索引错误 : list index out of range in array search

c - 我不知道这个程序有什么问题。它应该在c中将二进制转换为十进制

python - 使用 Python ORM 的交叉制表(列联表)?

python "or"当其中一个变量可能不存在时?

python - 为什么在与组匹配时 findall 不返回整个匹配项?

java - 将字符串转换为 double 总是给我错误的表示

java - 在电子邮件中发送的 java 字符串的格式冒号

python - For loop in 2 arrays of same size 给出 ValueError

python - 字典按月中的天数(键)在 python 中排序

python - 如何在 Pandas 中的 "day period"上覆盖数据以进行绘图