Quantcast
Channel: Linux Guides, Tips and Tutorials | LinuxScrew
Viewing all articles
Browse latest Browse all 314

Printing Text in Python Without a Newline

$
0
0

This short tutorial will show you how to print text in Python, without a new line appearing.

The Newline Character in Python

In Python, newlines are represented by a \ (backslash) followed by n:

\n

You Can Add New Lines to Printed Strings

The \n won’t be shown to the user – a new line will be inserted instead (unless an escape character is added).

So, when the below code is executed:

print("Linux\nScrew")

It will appear as:

Linux
Screw

Print Statements Add a Newline By Default

By default, a newline is appended to all output generated by the print statement:

print("Linux")
print("Screw")

The above will print:

Linux
Screw

…to the console – with the newline inserted automatically.

Printing without a newline

To print without newlines, simply add the end option to your print statements:

print("Linux", end="")
print("Screw", end="")

This will output:

LinuxScrew

…without a newline in sight. The end option tells the print function what to append to the end of its output. By default it’s a newline (\n), but by overriding it with an empty string, the newline is removed.

View the original article from LinuxScrew here: Printing Text in Python Without a Newline


Viewing all articles
Browse latest Browse all 314

Trending Articles