When printing to the console in Python, the default action for the print function is to append a new line to the end of each output.
This may not always be desirable, especially when you want your output formatted in a certain way. In this tutorial, we will discuss how you can prevent the print function from advancing to a new line in Python.
Using print function in Python
The default behavior of the Python print function is to output data to the console and then add a new line character at the end, which moves the cursor to the next line.
This behavior is controlled by an optional parameter in the print function, end, which specifies the string that is appended after the last value.
Printing without advancing to the next line
You can prevent Python from appending the newline character by specifying a different value for the end parameter.
To print without a newline in Python 3.x, use the following progression of steps:
- Set the argument end to an empty string.
1 |
print("Hello World!", end="") |
- end=”” specifies that we want an empty string after the last value, effectively suppressing the default newline character.
Full Code
The complete code to demonstrate this is as follows:
1 2 |
print("Hello", end="") print("World!") |
Output
1 |
HelloWorld! |
Conclusion
In conclusion, the print function in Python is highly customizable and can be adjusted to fit many different scenarios. Using the end parameter, you can control whether an extra character, such as a newline, is appended after the last output value.
By setting end=”” you can prevent Python from advancing the print function to a new line. This is useful when you want to format your output in a specific way.