Understanding splitlines() Function in Python

Understanding splitlines() Function in Python

5 mins read353 Views Comment
Updated on Oct 3, 2023 11:53 IST

This blog explains Spiltlines() function in Python. We have explained this concept with the help of example. Let’s understand!

2023_05_Copy-of-Copy-of-Feature-Image-Templates-42.jpg

The splitlines() method in Python creates a string list by dividing the provided string at designated line breaks. In this article, we will discuss the splitlines() function and understand its use with the help of examples. We will be covering the following sections:

Explore free Python courses

Introduction to splitlines() Function in Python

In Python, splitlines() is a built-in function to split a string into a list of strings based on line breaks. It looks for line breaks, such as newline character “\n”, carriage return “\r”, or a combination of both “\r\n”, and splits the string accordingly. The resulting list contains each original string line as a separate element.

Check out: Python Courses Online

The splitlines() function can be called on a string object and takes no arguments. It is particularly useful when working with text files or multi-line strings. This function allows us to quickly and easily split the text into lines for further processing or analysis. 

Syntax of splitlines()

The syntax of splitlines() function in Python is given as:

string.splitlines([keepends]) 

Parameters of splitlines()

The splitlines() method has an optional parameter called “Keepends”. It is a Boolean type parameter with a default value of False. This parameter determines whether to include the line break characters in the resulting list. If Keepends is set to True, the line break characters are included in the resulting list. 

Return Value of splitlines()

When the splitlines() function is given a string that contains line breaks, it returns a list of the individual lines separated by commas. However, if the input string passed to the function is empty or contains no line breaks, the function will return a list with one element: the original string. 

Note: The splitlines() method can only be used with string objects, not other data types.

Understanding isdecimal() Method in Python
What is Partition() Function in Python?
Learn the max() Function in Python with Examples
Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

– / –
40 hours
– / –
5 days
– / –
3 days
3 K
3 weeks
– / –
4 days
– / –
20 hours
– / –
2 months
Free
6 weeks

Examples of Using the splitlines() Function in Python

Example 1: Splitting a Multi-line String


 
para = """Hello There !
Welcome to
Shiksha
Online
"""
print(para.splitlines())
Copy code

Output:

['Hello There !', 'Welcome to', 'Shiksha', 'Online']

This code defines a multi-line string called “para” that contains several lines of text.

The code then uses the splitlines() method to split the string into a list of lines. xperts printed using the “print()” function. As we can see, the splitlines() method has separated the original string into a list of four individual lines, removing the line break characters that separated them.

Example 2: Splitting a Text File into Lines


 
with open('file.txt', 'r') as f:
lines = f.read().splitlines()
print(lines)
Copy code

In this example, we open a text file named “file.txt” in read mode using the “with open()” statement. We then read the contents of the file using the read() method and split the resulting string into a list of lines using the splitlines() method. Finally, we print out the resulting list of lines.

Example 3: Removing Empty Lines From a List 


 
lines = ['line 1', '', 'line 2', '', 'line 3']
filtered_lines = [line for line in lines if line]
print(filtered_lines)
Copy code

Output:

['line 1', 'line 2', 'line 3']

In this example, we have a list of strings representing lines of text. Some of the lines are empty strings. We can use the splitlines() function to split each string into a list of lines, and then use a list comprehension to remove the empty lines from the resulting list.

Example 4: Keeping the Line Break Characters in the Resulting List


 
text = '''This is line 1.
This is line 2.
This is line 3.'''
lines = text.splitlines(keepends=True)
print(lines)
Copy code

Output:

['This is line 1.\n', 'This is line 2.\n', 'This is line 3.'] 

In this example, we use the splitlines() method with the “keepends” parameter set to True to include the line break characters in the resulting list of lines. We then print out the resulting list. 

Example 5: Processing a Multi-Line String 


 
text = 'Hello\nWorld\n'
lines = text.splitlines()
processed = [line.upper() for line in lines]
print(processed)
Copy code

Output:

['HELLO', 'WORLD'] 

In this example, we have a multi-line string with line breaks represented by the “\n” character. We use the splitlines() method to split the string into a list of lines, and then use a list comprehension to convert each line to uppercase. 

Conclusion

The splitlines() function is a useful method in Python for splitting a string into a list of strings based on line breaks. This can be particularly useful when dealing with multi-line text data. The function is simple to use and has an optional parameter that allows you to include line break characters in the resulting strings.Hope this article was helpful for you in understanding how and why the splitlines() function is used in Python. If you wish to learn more about Python and practice Python programming, you can explore related articles here.

FAQs

What is the purpose of the splitlines() function in Python?

The splitlines() function is used to split a string into a list of strings, where each element of the list represents a line in the original string. The function looks for line breaks in the string and splits it accordingly.

What is the default behavior of the splitlines?

The default behavior of the splitlines() function is to split the string at line breaks and return a list of strings, without including the line break characters in the resulting strings.() function

Can the splitlines() function split a string based on a custom delimiter?

No, the splitlines() function can only split a string at line breaks, which are typically represented by the "n" character. To split a string based on a custom delimiter, you can use the split() method.

How can I include line break characters in the resulting strings when using the splitlines() function?

You can pass the optional "keepends" argument to the splitlines() function and set it to True. This will include the line break characters in the resulting strings.

What happens if I pass an empty string to the splitlines() function?

If you pass an empty string to the splitlines() function, it will return a list with a single empty string element.

Can the splitlines() function be used with multi-line strings?

Yes, the splitlines() function can be used with multi-line strings. It will split the string into a list of strings, where each element of the list represents a line in the original string.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio