Python Program to Print Output Without a Newline
In Python, a newline is represented by the escape sequence “\n”. It is used to indicate the end of a line and start a new line in a string or file. When the “\n” escape sequence is encountered in a string, it moves the cursor to the beginning of the next line when the string is printed or displayed. For example:
print("Hello\nWorld!")
Output:
Hello
World!
In the above example, the “\n” escape sequence is used to insert a newline between the words “Hello” and “World!” when the string is printed.
Python Code :
In Python, the print() function adds a newline character at the end of the output by default. However, you can prevent this by using the end parameter of the print() function. Here’s a Python program to print output without a newline:
# Print output without a newline
print("Hello, ", end='')
print("World!")
In this program, we first use the print() function to print the string “Hello, " without a newline. To do this, we set the end parameter of the print() function to an empty string (’’). This tells Python to not add a newline after the output. We then use another print() function to print the string “World!”, which will be printed immediately after “Hello, " on the same line.
You can also use other characters as the end parameter to separate the output. For example, to separate the output with a space instead of a newline, you can use end=’ ’ instead of end=’’. To separate the output with a comma and a space, you can use end=’, ’ instead.
# Print output with a different separator
print("Hello, ", end=', ')
print("World!")
In this program, we use the print() function to print the string “Hello, " with a comma and a space separator. We set the end parameter to ‘, ‘, which adds a comma and a space after “Hello, “. We then use another print() function to print the string “World!”, which will be printed immediately after “Hello, " with a comma and a space separator on the same line.