How to avoid printing newline in Python?



By default Python adds a new line when a text is printed using the print() method. We will see here how we can avoid the following −

Example

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

The output prints them in a new line −

Output

Demo
This is another demo text.

To avoid what we have shown above, use the end parameter.

Avoid printing newline - strings

In this example, we will see how we can avoid displaying newline while working around strings −

Example

# 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")

Output

We cannot
displaying this
in a single
line

We are displaying this in a single line

Avoid printing newline - numbers

In this example, we will see how we can avoid displaying newline while working around numbers −

Example

# 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 =""),

Output

5
10
15
20
5101520

Advertisements