How To Split Lines In Python

Splitting lines in a text file or a string is a common task in Python programming. In this tutorial, we will learn how to split lines in Python using different methods. These methods come in handy when you are trying to clean or preprocess your text data for further analysis.

Step 1: Split lines using the split() function

The split() function is one of the easiest ways to split a string or a text file. By default, it splits lines based on the whitespace, but you can also use a custom delimiter as an argument.

Here’s an example:

The output will be:

['Hello, world!', 'Welcome to the Python tutorial!']

This method works well when you have a string and want to split it into multiple lines.

Step 2: Use the readlines() method for text files

If you have a text file and would like to split its lines, you can use the readlines() method. This method reads the entire file into memory and splits it into lines automatically.

Here’s an example:

Create a file named “example.txt” with the following content:

Hello, world!
Welcome to the Python tutorial!

Python code:

The output will be:

['Hello, world!\n', 'Welcome to the Python tutorial!\n']

This method works well when you want to split lines in a text file.

Step 3: Use a loop to read lines one by one

If you have a large text file that cannot fit into memory, you can use a loop to read lines one by one without loading the entire file into memory.

Python code:

The output will be:

['Hello, world!', 'Welcome to the Python tutorial!']

Here we used strip() to remove the newline character from each line.

Full Code

Output

['Hello, world!', 'Welcome to the Python tutorial!']
['Hello, world!\n', 'Welcome to the Python tutorial!']
['Hello, world!', 'Welcome to the Python tutorial!']

Conclusion

In this tutorial, we learned how to split lines in Python using different methods. You can use the split() function to split a string, readlines() method to split lines in a text file, or a loop to read lines one by one. These methods are essential when working with text data in Python programming.