How to use splitlines in Python

In Python, splitlines() is a method of string objects used to split a string into a list according to different line endings such as newline (‘\n’), carriage return (‘\r’), or carriage return followed by newline (‘\r\n’). It returns a list containing each line as a separate string.

Here is an example of how to use the splitlines() method:

string = "Hello\nWorld\nPython"
lines = string.splitlines()
print(lines)

The output is:

['Hello', 'World', 'Python']

In the example above, the string “Hello\nWorld\nPython” is split into three lines using the splitlines() method and stored in a list.

The splitlines() method also has some optional parameters, such as keepends, with a default value of False. If you set the keepends parameter to True, the strings in the list will retain the newline characters at the end of each line. Here is an example with the keepends parameter:

string = "Hello\nWorld\nPython"
lines_with_ends = string.splitlines(keepends=True)
print(lines_with_ends)

The output is:

['Hello\n', 'World\n', 'Python']

In the example above, the splitlines(keepends=True) method preserves the newline characters at the end of each line of the string.

Leave a Reply 0

Your email address will not be published. Required fields are marked *