The easiest way to print anything without adding a newline automatically is to set the “end” parameter of the print() function to an empty string (“”).
By default, the print() function adds a newline character (\n) at the end of the output.
Sometimes, you need to print values without a newline when creating dynamic and formatted output. For example, if you are developing an app and you are stuck with an error, using formatted output allows you to easily debug the code and fix the error.
# Before using the "end" parameter print("First part,") print("and here's the second part.") # After using the "end" parameter # This print statement does not add a newline at the end print("First part,", end="") # The following print statement will continue on the same line print(" and here's the second part.")
Using stdout.write()
The stdout.write() method in the sys module does not add a newline character at the end of the output, unlike the print() function.
import sys # Writing a string to stdout without a newline sys.stdout.write("First part,") # Subsequent output will continue on the same line sys.stdout.write(" and here's the second part.") # Output: First part, and here's the second part.%
Both methods allow us to control how our output is formatted without the default newline behavior.