本文摘自php中文网,作者爱喝马黛茶的安东尼,侵删。
跨行的字面字符串可用以下几种方法表示。使用续行符,即在每行最后一个字符后使用反斜线来说明下一行是上一行逻辑上的延续。以下使用 \n 来添加新行:

1 2 3 4 5 6 7 8 9 10 | >>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
>>> print ( '"Isn\'t," she said.' )
"Isn't," she said.
>>> s = 'First line.\nSecond line.' # \n 意味着新行
>>> s # 不使用 print (), \n 包含在输出中
'First line.\nSecond line.'
>>> print (s) # 使用 print (), \n 输出一个新行
First line.
Second line.
|
以下使用 反斜线(\) 来续行:
1 2 3 4 5 6 | hello = "This is a rather long string containing\n\
several lines of text just as you would do in C.\n\
Note that whitespace at the beginning of the line is\
significant."
print (hello)
|
相关推荐:《Python视频教程》
注意,其中的换行符仍然要使用 \n 表示——反斜杠后的换行符被丢弃了。以上例子将如下输出:
1 2 3 | This is a rather long string containing
several lines of text just as you would do in C.
Note that whitespace at the beginning of the line is significant.
|
或者,字符串可以被 """ (三个双引号)或者 ''' (三个单引号)括起来。使用三引号时,换行符不需要转义,它们会包含在字符串中。以下的例子使用了一个转义符,避免在最开始产生一个不需要的空行。
1 2 3 4 5 | print ( "" "\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
"" ")
|
其输出如下:
1 2 3 | Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
|
如果我们使用"原始"字符串,那么 \n 不会被转换成换行,行末的的反斜杠,以及源码中的换行符,都将作为数据包含在字符串内。例如:
1 2 3 | hello = r"This is a rather long string containing\n\
several lines of text much as you would do in C."
print (hello)
|
将会输出:
1 2 | This is a rather long string containing\n\
several lines of text much as you would do in C.
|
以上就是python续行符是什么的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
c#如何调用Python
对Python中的xlsxwriter库简单分析
Python中的id()函数及读取list的方法介绍(代码示例)
Python的主要用途是什么
详解Python使用asyncio包处理并发的方法
Python如何输出平均成绩
Python中import有什么用法
Python中怎么定义一个类
Python如何使用正则表达式排除集合中字符的功能详解
Python中func什么意思
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » python续行符是什么