In Python, the splitlines()
method is a built-in string method used to split a multi-line string into a list of individual lines. It identifies line breaks in the string and separates the lines accordingly. The method is useful when you want to process each line of a multi-line string separately.
Here's the syntax of the splitlines()
method:
string.splitlines(keepends)
keepends
(optional): This parameter is a boolean value that determines whether to keep the line break characters at the end of each line. If keepends
is set to True
, the line break characters (e.g., \n
or \r\n
) will be retained; otherwise, they will be removed. By default, keepends
is set to False
.The splitlines()
method returns a list containing the individual lines of the original string.
Here's an example of how to use the splitlines()
method:
multiline_string = "This is line 1.\nThis is line 2.\nAnd this is line 3."
# Split the multi-line string into individual lines
lines = multiline_string.splitlines()
# Print each line separately
for line in lines:
print(line)
This is line 1.
This is line 2.
And this is line 3.
If you want to keep the line break characters, you can pass keepends=True
as an argument:
multiline_string = "This is line 1.\nThis is line 2.\nAnd this is line 3."
# Split the multi-line string into individual lines and keep line break characters
lines_with_breaks = multiline_string.splitlines(keepends=True)
# Print each line separately along with the line break characters
for line in lines_with_breaks:
print(line)
This is line 1.
This is line 2.
And this is line 3.
Keep in mind that the splitlines()
method does not modify the original string; it returns a new list of lines based on the line breaks present in the original string.