Online Tutorials & Training Materials | STechies.com
Register Login

Python: How to Print Without Newline or Space

|| || 0

Python: How to Print Without Newline or Space
Stechies

Python is among the extremely simple computer programming languages that are a favourite among various beginner programmers. It is a general-purpose programming language that comes with a design philosophy of easy readability. With a basic knowledge of programming, anyone can master Python in a matter of a few months.

Printing the output is probably the most common command in any programming language and among the first commands that you lean. Similarly, it is among the first commands you will learn in Python. However, unlike other programming languages that print several outputs in the same line without a new line command, Python by default prints every output on a different line. In order to print different outputs in the same line, you have to introduce certain changes in the print command.

Print Without Newline

Printing Without A Newline In Python3

In Python 3, print() is a function that prints output on different lines, every time you use the function. However, you can avoid this by introducing the argument end and assigning an empty string to it. This will prevent the next output from being printed in a new line.

 Input

# use the argument "end" to specify the end of line string

print("Good Morning!", end = '')
print("What a wonderful day!")

Output

# Good Morning!What a wonderful day!

Now to insert a space in your output, you have to use a space at the end of your first print function.

Input

# use the argument "end" to specify the end of line string and print with space

print("Good Morning! ", end = '')
print("What a wonderful day!")

Output

# Good Morning! What a wonderful day!

Printing Without A Newline In Python2

Unlike Python 3, Python 2 did not have the function end. To print output, you have to input print in the form of a statement. However, in this version of Python, every output was printed in the next line. In order to print in the same line, all you have to do is terminate your print statement with a comma.

Input

# print without a newline but with space

print "Good Morning!",
print "What a wonderful day!"

Output

# Good Morning! What a wonderful day!

Conclusion

With most other programming languages requiring the position of a new line being mentioned in the program, many first time users may find printing with Python a little inconvenient. However, it is actually time-saving as it automatically detects a new line in the output with every print function or statement. Whenever you need an output printed in the same line, all you need to do is introduce a comma in Python 2 or terminate your print function with the argument end. This simple addition will help you get rid of your new line woes!


Related Articles