一、多行编写“长字符串”
1.1 直接三引号””” “””
multi_line_string = """this is line number 1
this is line number 2
this is line number 3
this is line number 4"""
print(multi_line_string)
# this is line number 1
# this is line number 2
# this is line number 3
# this is line number 4
这种多行字符串的劣势在于:输入的时候换行,那么这个字符串在换行的位置插入了一个\n符号,所以严格来说并不能实现我们所说的
输出一行长字符串但是输入的形式是多行
。
注意,单双引号,输入形式不允许是多行但不加反斜杠符号。代码如下所示,出错了。
multi_line_string = "this is line number 1
this is line number 2
this is line number 3
this is line number 4"
print(multi_line_string)
# SyntaxError: EOL while scanning string literal
如果不想换行,可以在行尾添加反斜杠。
multi_line_string = """this is line number 1\
this is line number 2\
this is line number 3\
this is line number 4"""
print(multi_line_string)
# this is line number 1this is line number 2this is line number 3this is line number 4
1.2 单双引号和反斜杠
multi_line_string = "this is line number 1\
this is line number 2\
this is line number 3\
this is line number 4"
print(multi_line_string)
# this is line number 1this is line number 2this is line number 3this is line number 4
1.3 单双引号和圆括号
每一行字符串,都需要加一对单双引号;最后输出的是一行字符串。
multi_line_string = ("this is line number 1"
"this is line number 2"
"this is line number 3"
"this is line number 4")
print(multi_line_string)
# this is line number 1this is line number 2this is line number 3this is line number 4
将圆括号和反斜杠符配合,在每一次换行的位置加反斜杠,就可以在这多行字符串上只加一对单双引号了。
multi_line_string = ("this is line number 1\
this is line number 2\
this is line number 3\
this is line number 4")
print(multi_line_string)
# this is line number 1this is line number 2this is line number 3this is line number 4
1.4 易错点:禁止存在缩进
在编程的时候,如果处于if、for语句的代码块内,字符串在手动换行时可能会自动缩进;这时候编译器没办法把这些缩进去除,从而影响输出结果。
multi_line_string = """this is line number 1\
this is line number 2\
this is line number 3\
this is line number 4"""
print(multi_line_string)
# this is line number 1 this is line number 2 this is line number 3 this is line number 4
二、多行编写“长推导式”
要想多行形式写入长推导式,可以直接换行,比如下面的代码
class_list = [c for c in os.listdir(all_file_dir)
if os.path.isdir(os.path.join(all_file_dir, c))
and not c.endswith('Set')
and not c.startswith('.')]
同时,为了增强可读性 ,建议一块一块地换行,比如and逻辑语句的前一块和后一块。
三、多行编写“长序列”
只要你每一次换行不拆分一个单独的数,就不会出问题。
list1 = [1,
2,
3,
4]
print(list1)
# [1, 2, 3, 4]
由于换行不作为数与数之间的分隔符,所以下面的第二个代码块就出错了。
list1 = [1,
22,
3,
4]
print(list1) # [1, 22, 3, 4]
# ---------------------------------
list1 = [1,
2
2,
3,
4]
print(list1) # SyntaxError: invalid syntax
版权声明:本文为PSpiritV原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。