How to Use the Python String splitlines() Method

09/17/2021

Contents

In this article, you will learn how to use the Python String splitlines() method.

String splitlines() Method

The splitlines() method in Python is a built-in method for strings that splits a string at line breaks and returns a list of the resulting lines. This method is useful when you have a string that contains multiple lines and you want to separate them into individual strings.

Syntax

Here is the basic syntax for using the splitlines() method:

string.splitlines([keepends])
Parameters

keepends: Specifies whether to include the line break characters in the resulting strings. The default is False.

Example

Here’s an example:

text = "This is the first line.\nThis is the second line.\nAnd this is the third line."

lines = text.splitlines()

print(lines)

# Output: ['This is the first line.', 'This is the second line.', 'And this is the third line.']

In this example, we have a string text with three lines separated by line breaks (\n). We use the splitlines() method to split the string into individual lines, which are returned as a list of strings. We assign this list to the variable lines and then print it.

If we want to include the line break characters in the resulting strings, we can set the keepends parameter to True:

text = "This is the first line.\nThis is the second line.\nAnd this is the third line."

lines = text.splitlines(keepends=True)

print(lines)

# Output: ['This is the first line.\n', 'This is the second line.\n', 'And this is the third line.']

In this example, we get the same list of lines as before, but each line now includes its line break character (\n).