AppDividend
Latest Code Tutorials

Python line break: How to Print Line Break

0

The new line character in Python is used to mark the end of a line and the beginning of a new line. To create a string containing line breaks, you can use one of the following.

  1. Newline code \n(LF), \r\n(CR + LF).
  2. Triple quote ”’ or “””.
  3. With indent.

Let’s see the line break tutorial in detail.

Python line break

To do a line break in Python, use the parentheses or explicit backslash(/). Using parentheses, you can write over multiple lines. The preferred way of wrapping long lines is by using Python’s implied line continuation inside parentheses, brackets, and braces. 

Long lines can be divided over multiple lines by enclosing expressions in parentheses. These should be used in inclination to using a backslash for line continuation.

Let’s use the parentheses for a line break in Python.

x = 11
y = 22
z = 33
w = 44
u = 55

data = (x + y + z +
        w + u)
print(data)

Output

165

You can see that we got the sum of all the variables.

We can also use the explicit line break(\) to break the code in multiple lines and won’t give any error.

x = 11
y = 22
z = 33
w = 44
u = 55

data = x + y + z + \
        w + u
print(data)

And it will give the same output without any error.

You can use either parentheses or backslash depending on your scenario but be careful when using the backslash. The danger in using a backslash to end a line is that if whitespace is added after the backslash (which, of course, is very hard to see), the backslash is no longer doing what you thought it was.

In short, you can break lines in between parentheses and braces. Additionally, you can add the backslash character \ to a line to explicitly break it.

The New Line Character in Python

The new line character in Python is \n. It is made up of two characters:

  1. A backslash(\).
  2. The letter n.

If you see this character in a string, that means that the current line ends at that point, and a new line starts right after it.

By default, print statements add a new line character “behind the scenes” at the end of the string.

print("Expeli Armus")

The default value of the end parameter of the built-in print function is \n, so a new line character is appended to the string.

How to Print Without a New Line

We can change this default behavior by customizing the value of the end parameter of the print function.

print("harry", end="")
print("potter")

Output

harrypotter

The space will be added to the end of the string instead of the new line character \n, so the output of the two print statements will be displayed in the same line.

That’s it for this tutorial.

 

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.