在Python中,实现代码换行的方法主要有以下几种,可根据具体场景选择合适的方式:
一、使用反斜杠(\)
print('This is a very long line that spans multiple lines.' <b class="card40_2411__sup_5321" data-sup="sup">8
'It is split using a backslash and newline character.')
注意事项 :反斜杠需紧跟换行符,且不能出现在行首或行尾。
二、使用括号()
将多行代码包裹在圆括号内,Python会将其视为一个整体。
print(( 'This is line 1' + ' and this is line 2' ))
print(( 'This is line 1' + ' and this is line 2' ))
注意事项 :括号内必须以冒号(:)或逗号(,)结尾,且换行符需在行末。
三、使用换行符(\n)
在字符串中直接添加换行符,适用于多行字符串的定义。
This is line 2"""
print(text)
四、使用print()
函数的end
参数
通过设置end=''
参数,print()
函数会在输出后不换行,从而实现多行输出。
扩展 :结合换行符使用:
print("This is line 1", end="\nThis is line 2")
print("This is line 1", end="\nThis is line 2")
五、使用分号(;)
在同一行使用分号分隔多条语句,但无法实现真正意义上的换行
print("This is line 1"); print("This is line 2")