假设我有一大段文字,比如说
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/