Wednesday, January 15, 2025
HomeTechHow to Print without newline in Python?

How to Print without newline in Python?

In Python, by default, the print() function adds a newline (\n) at the end of the output, causing each print statement to print on a new line. However, if you want to print without a newline, you can modify the behavior using the end parameter in the print() function.

1. Using the end Parameter

The end parameter in the print() function allows you to specify what should be printed at the end of the output. By default, it is set to "\n" (newline), but you can change it to any string, including an empty string "", to prevent the newline from being added.

# Printing without newline
print("Hello,", end=" ")
print("world!")

Output:

Hello, world!

In this example, the end=" " ensures that a space is printed after the first print() statement, and no newline is added between the two print statements.

See also  How to open TIF or TIFF files on Android

2. Using end="" (Empty String)

If you want to print multiple statements on the same line with no space, you can use end="".

# Printing without space or newline
print("Hello", end="")
print("World!")

Output:

HelloWorld!

3. Customizing end with Other Characters

You can also customize the separator after each print statement by setting the end parameter to any character or string you prefer.

# Printing with a comma and no newline
print("Apple", end=", ")
print("Banana", end=", ")
print("Orange")

Output:

Apple, Banana, Orange

4. Printing in a Loop without Newlines

You can use the end parameter to print values in a loop without adding a newline each time.

# Print numbers 1 to 5 on the same line
for i in range(1, 6):
    print(i, end=" ")

Output:

1 2 3 4 5

Summary

  • Use end="" to prevent print() from adding a newline at the end of the output.
  • You can also customize the separator with any string (e.g., end=" " for a space or end=", " for a comma).
Previous article
Next article
RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x