如何编写多行Python字符串:三重引号与括号“技巧”

2 投票
3 回答
1475 浏览
提问于 2025-04-18 16:23

我通常是这样写多行字符串的:

>>> s = """hello this is the first line
... and this is the second"""
>>> s
'hello this is the first line\nand this is the second'

但最近我遇到了这个:

>>> s = ( 'hello this is the first line'
... 'and this is the second' )
>>> s
'hello this is the first lineand this is the second'

好吧,line\nand 变成了 lineand。这两种写法还有其他区别吗?我什么时候应该使用第二种呢?

3 个回答

-2
>>> s = ( 'hello this is the first line'
... 'and this is the second' )
>>> s = ( 'hello this is the first line''and this is the second' )
>>> s = ( 'hello this is the first lineand this is the second' )
>>> s = 'hello this is the first lineand this is the second'
>>> s
'hello this is the first lineand this is the second'

结果是

3

第二种形式其实就是一种隐式的连接方式。你会在需要写很长的字符串时使用它,这个字符串本来应该在一行上,但为了让它在代码编辑器里更容易阅读(因为大多数编辑器一次只能显示大约80到100个字符),你可以这样做。

3

首先要说明的是,“括号技巧”其实并不是多行字符串,而只是隐式的行连接。Python 这种行为的具体说明可以在这里找到。

你写的方式是不同的,所以你应该使用哪种方式,取决于你是否想在字符串中换行。

如果你想用括号的方式,并且在每一行都明确放入\n这个字符,其实有个更好的选择,就是使用textwrap.dedent

撰写回答