通过允许字符串跨越多行,包括逐字NEWLINE,TAB和任何其他特殊字符,Python的三重引号得以解决。
三重引号的语法包含三个连续的单引号或双引号。
#!/usr/bin/python para_str = """this is a long string that is made up of several lines and non-printable characters such as TAB ( \t ) and they will show up that way when displayed. NEWLINEs within the string, whether explicitly given like this within the brackets [ \n ], or just a NEWLINE within the variable assignment will also show up. """ print para_str
输出结果
执行以上代码后,将产生以下结果。
请注意,如何将每个特殊字符都转换为其打印形式,一直到“ up”之间的字符串末尾的最后一个NEWLINE。和三重引号。另请注意,NEWLINE要么在行的末尾显式回车,要么其转义码(\ n)-
this is a long string that is made up of several lines and non-printable characters such as TAB ( ) and they will show up that way when displayed. NEWLINEs within the string, whether explicitly given like this within the brackets [ ], or just a NEWLINE within the variable assignment will also show up.
原始字符串根本不会将反斜杠视为特殊字符。您输入到原始字符串中的每个字符都保持您编写它的方式-
#!/usr/bin/python print 'C:\\nowhere'
输出结果
执行以上代码后,将产生以下结果-
C:\nowhere
现在,让我们使用原始字符串。我们将表达式放在r'expression'中,如下所示:
#!/usr/bin/python print r'C:\\nowhere'
输出结果
执行以上代码后,将产生以下结果-
C:\\nowhere