使用python的print(“\”)

2024-06-25 23:02:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在阅读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     
""")

我只是不明白\在这里扮演什么角色。我知道我的问题有点基本,但是否有人有一个例子,根据\的使用情况而不同。你知道吗


Tags: ofthetostringisdocumentationmultiplethis
3条回答

开头的\是为了确保开头没有换行符。它本质上把新行作为它自己的转义字符,所以它不会将它转换成'\n'(换行符):

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

所以把反斜杠放在前面就好像根本没有间隙一样。你知道吗

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

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

试试看!你知道吗

>>> 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  

相关问题 更多 >