Python str.splitlines() function
In Python, the str.splitlines()
method is used to split a string into a list of lines. This method is particularly useful for processing multiline strings, as it separates the string at line breaks and returns a list containing each line as a separate element.
Syntax
- keepends (optional): A boolean value that determines whether to include the line break characters (
\n
,\r
, or\r\n
) at the end of each line in the resulting list.- If
True
, the line breaks are included in the resulting list. - If
False
(the default), the line breaks are not included.
- If
Example Usage
- Basic usage:
- Including line breaks:
If you want to keep the line breaks in the resulting list, you can set keepends
to True
:
- Different line break characters:
The splitlines()
method can handle different types of line breaks, including carriage returns (\r
) and a combination of both (\r\n
):
- Empty string:
If the string is empty, the result will be an empty list:
- Trailing newlines:
If the string ends with a newline character, splitlines()
will handle it gracefully. By default, the trailing newline is not included:
Summary
- Use
str.splitlines()
to split a string into a list of lines based on line break characters. - The
keepends
parameter allows you to control whether the line breaks are included in the resulting list. - This method is useful for processing multiline strings, such as reading from text files or handling user input with multiple lines.