Python String splitlines()

Python String.splitlines() is used to split a string into lines. The splitlines() method splits this string at line breaks and returns the parts as a list.

In this tutorial, we will learn the syntax and examples for splitlines() method of String class.

Syntax

The syntax to call splitlines() method on string x in Python is

x.splitlines(keepends)

where

ParameterRequired / OptionalDescription
keependsOptionalA boolean value. If True, keeps line breaks at end of the lines in the resulting list. Default value is False.
ADVERTISEMENT

Examples

In the following program, we take a string in x, and split this string into lines using splitlines() method.

Example.py

x = 'Hello World.\nWelcome!\nPython Tutorial.'
result = x.splitlines()
print(result)
Try Online

Output

['Hello World.', 'Welcome!', 'Python Tutorial.']

Now, let us pass True for keepends parameter to splitlines() method.

Example.py

x = 'Hello World.\nWelcome!\nPython Tutorial.'
result = x.splitlines(keepends=True)
print(result)
Try Online

Output

['Hello World.\n', 'Welcome!\n', 'Python Tutorial.']

The line breaks are retained for the lines in the resulting list.

Conclusion

In this Python Tutorial, we learned how to split a string into lines using splitlines() method, with examples.