Python 如何避免换行打印

Python 如何避免换行打印

默认情况下,当使用print()方法打印文本时,Python会添加一个新行。我们将在这里看到如何避免下面的情况 –

示例

print("Demo")
print("This is another demo text.")

输出会将它们打印在新的一行上 –

输出

Demo
This is another demo text.

为了避免我们上面展示的问题,可以使用end参数。

避免打印换行 – 字符串

在这个示例中,我们将看到如何在处理字符串时避免显示换行符:

示例

# Displaying in new lines
print("We cannot")
print("displaying this")
print("in a single")
print("line")

print("")

# Displaying in a single line i.e. avoiding new lines
print("We are ",end =""),
print("displaying this ",end =""),
print("in a single ",end =""),
print("line")

输出

We cannot
displaying this
in a single
line

We are displaying this in a single line

避免打印换行 – 数字

在这个示例中,我们将看到如何在处理数字时避免显示换行符−

示例

# Displaying in new lines
# Defining a list
my_arr = [5, 10, 15, 20, 25, 30]

# printing the list content
for i in range(4):
    print(my_arr[i]),

print("")

# Displaying in a single line i.e. avoiding new lines
# Defining a list
my_arr = [5, 10, 15, 20, 25, 30]

# printing the list content
for i in range(4):
    print(my_arr[i], end =""),

输出

5
10
15
20
5101520

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程