Ora

How do you change the new line in Python?

Published in Python Newlines 4 mins read

In Python, you change the newline behavior primarily through the print() function's end keyword argument or by explicitly using the \n escape sequence within strings.

Understanding Python's Default Newline Behavior

By default, the built-in print() function automatically adds a newline character (\n) at the end of its output. This means each print() call will typically display its content on a new line.

For example:

print("First line")
print("Second line")

Output:

First line
Second line

This default behavior is convenient for displaying information line by line, but Python offers straightforward ways to modify or override it.

Modifying the print() Function's Newline

The print() function comes with an optional keyword argument called end, which determines what character(s) are printed at the end of the output. By default, end is set to '\n'.

Removing the Default Newline

To prevent print() from adding a newline, you can set the end argument to an empty string (""). This is particularly useful when you want to print multiple items on the same line without any separator or to control the exact spacing between printed elements.

print("Hello", end="")
print("World!")

Output:

HelloWorld!

Changing the Newline Character

You can also specify any other string as the value for the end argument. This allows you to terminate the printed output with a space, a comma, or any custom sequence of characters instead of a newline.

print("Item 1", end=" | ")
print("Item 2", end=" | ")
print("Item 3") # The last print uses the default newline

Output:

Item 1 | Item 2 | Item 3

For more details on the print() function, refer to the Python documentation.

Explicitly Adding Newlines with \n

The newline character, denoted by \n, is an escape sequence that can be embedded directly within a string. When Python encounters \n in a string, it interprets it as a command to start a new line at that point.

This is useful for creating multi-line strings without needing multiple print() statements or when formatting text that needs to span several lines.

message = "This is the first line.\nThis is the second line.\nAnd this is the third."
print(message)

Output:

This is the first line.
This is the second line.
And this is the third.

For more on string literals and escape sequences, consult the Python Language Reference.

Controlling Newlines in Iterations

When iterating over data, you often need precise control over newlines. Using the end argument within a loop is a common pattern.

numbers = [1, 2, 3, 4, 5]
for num in numbers:
    print(num, end=", ")
print("Done!") # This print will add a final newline after "Done!"

Output:

1, 2, 3, 4, 5, Done!

Combining Elements with Custom Separators (str.join())

For joining a list of strings into a single string with a specific separator (including a newline), the str.join() method is highly efficient and recommended.

lines = ["Apples", "Bananas", "Cherries", "Dates"]
# Join the list items with a newline character
multi_line_string = "\n".join(lines)
print(multi_line_string)

Output:

Apples
Bananas
Cherries
Dates

The str.join() method is excellent for dynamically generating formatted output. Learn more about it in the Python Standard Types documentation.

Summary of Newline Control Methods

Here's a quick overview of the common ways to handle newlines in Python:

Method Description Example
print(..., end="") Prevents the print() function from adding its default newline, effectively printing without a line break. print("Hello", end=""); print("World")
print(..., end="<STR>") Replaces the default newline with a specified string <STR> as the terminator. print("Part 1", end="---"); print("Part 2")
"\n" (escape sequence) Embeds a literal newline character directly within any string to force a line break at that point. print("Line A\nLine B")
"\n".join(list_of_strings) Joins elements of an iterable (like a list) into a single string, using \n as the separator. fruits = ["Apple", "Orange"]; print("\n".join(fruits))

Understanding these methods provides full control over how your Python programs display text and manage line breaks.