Python String splitlines()


Python String splitlines() method

Python String splitlines() method splits the given string at line breaks and returns a list.

Consider that given string is in x.

x = "apple\nbanana\ncherry"

Then the return value of x.splitlines() is

['apple', 'banana', 'cherry']

In this tutorial, you will learn about String splitlines() method, its syntax, and how to use this method in Python programs, with examples.

Syntax of splitlines() method

The syntax of String splitlines() method in Python is given below.

string.splitlines(keepends)

Parameters

The splitlines() method takes three parameters.

ParameterDescription
keependsOptional
A boolean value.
If keepends is given and True, then line breaks are included in the resulting list.
Default value is False.

Return value

The string splitlines() method returns a list object, with the string literals created by the split at line breaks.

Examples

1. splitlines() - Split string at line breaks in Python

In the following program, we take a string in variable my_string, and split the string at line breaks using String splitlines() method.

The splitlines() method returns a list of split lines. We shall store the list in lines, and print it to output.

Python Program

my_string = "apple\nbanana\ncherry"

lines = my_string.splitlines()

print(lines)

Output

['apple', 'banana', 'cherry']

Explanation

apple\nbanana\ncherry
      ↑       ↑
     line-breaks
apple  banana  cherry

2. splitlines(keepends) - keepends set to True

In the following program, we shall pass True for the keepends parameter, and observe the returned list.

Python Program

my_string = "apple\nbanana\ncherry"

lines = my_string.splitlines(True)

print(lines)

Output

['apple\n', 'banana\n', 'cherry']

Since we specified keepends=True, the line breaks are included in the resulting list.

Summary

In this tutorial of Python String Methods, we learned about String splitlines() method, its syntax, and examples covering scenarios of different combinations of arguments.