字符串拼接:在Python代码中放入大量文本

8 投票
3 回答
11016 浏览
提问于 2025-04-17 14:05

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

喜马拉雅朝圣的第三次也是最后一次轮回探讨了神圣空间的主题,展示了一对宏伟的大型曼荼罗画。这些画是一个三维建筑空间的二维表现,那里居住着特定的神灵。这些画作可以追溯到十四和十六世纪,生动的色彩展现了神灵赫瓦哲的宇宙观。还有几幅画描绘了不同藏传佛教派别的历史老师。

在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代码中,而不产生多余的空格?

我想要的答案不是:把整段文字放在一行上。

我需要添加的文本超过一行,但又不想增加额外的空格。

3 个回答

0

textwrap.dedent 这个功能可以帮你去掉文本开头多余的空格,而且不会影响你原本的缩进格式。

0

有几种方法可以做到这一点。当你有多个字符串,中间只有空格时,编译器会把它们合并成一个字符串,就像之前说的那样。你也可以用\来表示行的结束,像这样。

SomeText="Something" \
         "Something else"

或者

SomeText="Something" + \
         "Something else"

不过这样做的缺点是你必须记得在每一行的末尾加上\。一般来说,用+来连接很多字符串并不是个好主意,因为每找到一个+,就会复制一次字符串,而字符串是不可变的,这样会耗费很多时间。相反,可以考虑使用str.join,像这样。

SomeText="\n".join(["Something",
                  "Something else",
                  "Last Item"])

值得注意的是,这种方法还有一个好处,就是你可以根据需要把" "替换成其他分隔符(比如换行符或者不加任何字符)。

21

当你使用三重引号字符串时,你不需要缩进:

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中,连续的字符串会自动连接在一起(可以查看字符串字面量连接)。

当然,你也可以使用+符号来明确地连接字符串,但最好用括号把它们放在一起,形成一个表达式:

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

另一种方法是在行末使用反斜杠:

foo = "This is not " \
    "recommended"

不过我觉得使用括号和字符串字面量连接更容易阅读。

撰写回答