In Python, adding a new line is a common task when working with strings or file manipulations. This tutorial will guide you through different methods to add a new line in Python. We will discuss using the newline character, using triple quotes for multi-line strings, and adding a new line when writing to a text file.
Step 1: Using the newline character (\n)
The simplest way to add a new line in Python is to use the newline character, represented by \n
. This special character, when used within a string, will create a new line at the place it is located. For example, let’s print a multi-line string using the newline character:
1 |
print("Hello, world!\nWelcome to the Python tutorial!") |
This code will display the following output:
Output:
Hello, world! Welcome to the Python tutorial!
Step 2: Using triple quotes for multi-line strings
Another approach to create a multi-line string in Python is to use triple quotes ("""
or '''
). This method allows you to create a string that spans across multiple lines without the need to insert the newline character. Here’s an example:
1 2 3 4 5 |
multiline_string = """Hello, world! Welcome to the Python tutorial! Have a great day!""" print(multiline_string) |
The code results in the following output:
Output:
Hello, world! Welcome to the Python tutorial! Have a great day!
Step 3: Adding a new line when writing to a text file
When working with text files, it’s often necessary to add new lines to separate data or improve readability. To do this, you can simply add the newline character (\n
) at the end of the text you want to write to the file, and Python will automatically start writing on a new line.
For example, let’s create a file named example.txt
and write some text to it with new lines:
1 2 3 4 |
with open("example.txt", "w") as file: file.write("Hello, world!\n") file.write("Welcome to the Python tutorial!\n") file.write("Have a great day!") |
This code will write the following content to the example.txt
file:
Hello, world! Welcome to the Python tutorial! Have a great day!
Conclusion
In this tutorial, you have learned three ways to add a new line in Python, using the newline character, triple quotes for multi-line strings, and writing new lines to a text file. These methods will help you handle multi-line strings, improve code readability, and properly format text files.
Full code:
1 2 3 4 5 6 7 8 9 10 11 |
print("Hello, world!\nWelcome to the Python tutorial!") multiline_string = """Hello, world! Welcome to the Python tutorial! Have a great day!""" print(multiline_string) with open("example.txt", "w") as file: file.write("Hello, world!\n") file.write("Welcome to the Python tutorial!\n") file.write("Have a great day!") |