What is the string.splitlines() method in Python?
The splitlines() method in Python splits a string at the line break characters (\n, \r, \r\n, etc.) and returns the split strings as a list.
Refer here for details on link break characters.
If the string contains no line break character, a list with the string source as a single item is returned.
Syntax
string.splitlines([keepends])
Arguments
keepends: An optional Boolean value. If we set this to True, the line break characters are included in the split string. By default, it is False.
Code
Example 1
# Created a stringtest_str = " I learn at Educative.io \n This is awesome. \r\n Edpresso is super simple."# calling splitlines methodlist_of_split_str = test_str.splitlines()#printing the split stringsfor split_str in list_of_split_str:print(split_str)
Explanation 1
In the code above, we create a test_srt string. The test_str string contains the \n and \r\n line break characters.
Then, we call the splitlines() method on the test_str string, and store it in list_of_split_str.
The for loop statement iterates over the list_of_split_str and prints the result.
Code
Example 2
Include line break characters in the split strings.
# Created a stringtest_str = " I learn at Educative.io \n This is awesome. \r\n Edpresso is super simple."include_line_break = True;list_of_split_str = test_str.splitlines(include_line_break)print(list_of_split_str)
Explanation 2
In the code above, we call the splitlines() method on the test_str string.
The True keyword specifies that the line break characters are to be included in the split strings.
Output is a single string because of the optional True parameter.
Code
Example 3
String without a line break character:
# Created a stringtest_str = " I lean at Educative.io."# calling splitlines methodlist_of_split_str = test_str.splitlines()print(list_of_split_str)
Explanation 3
In the code above, the test_str string contains no line break character.
When we call the splitlines() method, we will get a list with the test_str as a single element in it.
Refer here for more details.