温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python续行符的使用示例

发布时间:2020-11-18 13:52:21 来源:亿速云 阅读:522 作者:小新 栏目:编程语言

这篇文章给大家分享的是有关python续行符的使用示例的内容。小编觉得挺实用的,因此分享给大家做个参考。一起跟随小编过来看看吧。

跨行的字面字符串可用以下几种方法表示。使用续行符,即在每行最后一个字符后使用反斜线来说明下一行是上一行逻辑上的延续。

以下使用 \n 来添加新行:

>>> '"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.

以下使用 反斜线(\) 来续行:

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)

注意,其中的换行符仍然要使用 \n 表示——反斜杠后的换行符被丢弃了。以上例子将如下输出:

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.

或者,字符串可以被 """ (三个双引号)或者 ''' (三个单引号)括起来。使用三引号时,换行符不需要转义,它们会包含在字符串中。以下的例子使用了一个转义符,避免在最开始产生一个不需要的空行。

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

如果我们使用"原始"字符串,那么 \n 不会被转换成换行,行末的的反斜杠,以及源码中的换行符,都将作为数据包含在字符串内。例如:

hello = r"This is a rather long string containing\n\
several lines of text much as you would do in C."
print(hello)

将会输出:

This is a rather long string containing\n\
several lines of text much as you would do in C.

感谢各位的阅读!关于python续行符的使用示例就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI