使用 python 的 print("""\""")

Using python's print("""\""")

我正在阅读 python documentation 并且偶然发现了这个:

String literals can span multiple lines. One way is using triple-quotes: """...""" or '''...'''. End of lines are automatically included in the string, but it’s possible to prevent this by adding a \ at the end of the line. The following example:

print("""\
Usage: thingy [OPTIONS]  
 -h                        Display this usage message
 -H hostname               Hostname to connect to     
""")

我只是不明白 \ 在这里扮演什么角色。我知道我的问题有点基础,但是有没有人有一个根据 \ .

的使用而产生不同结果的例子

试试吧!

>>> print("""\
... Usage: x
... """)
Usage: x

>>> print("""
... Usage: x
... """)

Usage: x

第一行末尾的 \ 可防止输出以空行开头,因为正如您引用的那样:

End of lines are automatically included in the string

除非它们已使用 \ 转义。

\用于否定行尾。在这种情况下换行符

代码:

print("""\
Usage: thingy [OPTIONS] \
-h                        Display this usage message\
-H hostname               Hostname to connect to \
""")

输出:

Usage: thingy [OPTIONS]  -h                        Display this usage message -H hostname               Hostname to connect to 

现在不否定换行符

代码1:

print("""\
Usage: thingy [OPTIONS]  
-h                        Display this usage message
-H hostname               Hostname to connect to     
""")

输出 1:

Usage: thingy [OPTIONS]  
-h                        Display this usage message
-H hostname               Hostname to connect to  

开头的\是为了保证开头没有换行符。它本质上将换行符作为自己的转义字符,因此不会将其变成 '\n' (换行符):

>>> print("""\ 
... Hello""")
Hello
>>> print("""
... Hello""")
                  <-- Notice the newline
Hello
>>> 

所以把反斜杠放在前面就等于没有空隙。

以下代码段产生相同的结果:

>>> print("""Hello
... World""")
Hello
World
>>> print("""\
... Hello
... World""")
Hello
World
>>> 

它只是让它忽略该字符串中的新行。例如,我的输出是

"Usage: thingy [OPTIONS]
 -h                        Display this usage message
 -H hostname               Hostname to connect to"

但是,如果没有它,我的输出是

"

Usage: thingy [OPTIONS]
 -h                        Display this usage message
 -H hostname               Hostname to connect to"