如何在Python中插入新行(换行) n在 Python 中,插入新行(即换行)可以通过多种方式实现,但最常用的方法是在字符串末尾添加换行符。


在 Python 中,插入新行(即换行)可以通过多种方式实现,但最常用的方法是在字符串末尾添加换行符。


一、使用 \n 插入新行

在 Python 中,\n 被用作换行符。你可以在任何字符串的末尾添加 \n 来表示字符串的结束和新的一行的开始。

print("Hello, World!\nThis is a new line.")

上面的代码会输出两行:

二、在字符串中嵌入多个换行

可以在字符串中嵌入多个 \n 来创建多个新行。

print("First line.\nSecond line.\nThird line.")

 

三、使用三引号字符串

对于需要跨越多行的字符串,你可以使用三引号(''' 或 """)来定义字符串,这样你就可以在字符串中直接包含换行,而无需在每个换行处都添加 \n

multi_line_string = """This is the first line. 
This is the second line. 
This is the third line.""" 
 
print(multi_line_string)

 

作者:gabadout原文地址:https://blog.csdn.net/jjjjjjjjncdfg/article/details/140468274

%s 个评论

要回复文章请先登录注册