Python string Method - splitlines()
The splitlines()
method is a built-in string method in Python that splits a string into a list of substrings based on line breaks.
The syntax for using splitlines()
method is as follows:
string.splitlines(keepends)
Here, string
is the original string, and keepends
is an optional parameter that specifies whether to include the line break characters in the resulting substrings. If keepends
is True
, the line break characters are included. If keepends
is False
(default), the line break characters are removed.
The method returns a list containing the resulting substrings.
Here's an example of using the splitlines()
method:
string = "Hello\nWorld\n" substrings = string.splitlines() print(substrings)
Output:
['Hello', 'World']
In the example above, the splitlines()
method was used to split the original string "Hello\nWorld\n"
based on the line breaks. The resulting list is stored in the variable substrings
, which contains the two substrings: "Hello"
and "World"
. Note that the line break characters were removed by default. If you want to include the line break characters, you can set the keepends
parameter to True
.