Borislav Hadzhiev
Last updated: Jun 26, 2022
Check out my new book
Use the str.splitlines()
method to split a string by \r\n
, e.g.
my_list = my_str.splitlines()
. The splitlines
method splits the string on
each newline character and returns a list of the lines in the string.
my_str = 'one\r\ntwo\r\nthree' result = my_str.splitlines() print(result) # 👉️ ['one', 'two', 'three']
The str.splitlines method splits the string on newline characters and returns a list containing the lines in the string.
The method does not include the line breaks, unless the keepends
argument is
set to True
.
my_str = 'one\r\ntwo\r\nthree' result = my_str.splitlines() print(result) # 👉️ ['one', 'two', 'three'] # 👇️ ['one\r\n', 'two\r\n', 'three'] print(my_str.splitlines(True))
The str.splitlines
method splits on various line boundaries, e.g. \n
, \r
,
\r\n
, etc.
my_str = 'one\rtwo\r\nthree\n' result = my_str.splitlines() print(result) # 👉️ ['one', 'two', 'three']
If the string ends with a newline character, the splitlines()
method removes
it, as opposed to the str.split()
method.
my_str = 'one\r\ntwo\r\nthree\r\n' result = my_str.splitlines() print(result) # 👉️ ['one', 'two', 'three'] # # 👇️ ['one', 'two', 'three', ''] print(my_str.split('\r\n'))
If there is whitespace between the text and the newline characters, use the
str.strip()
method to remove it.
my_str = 'one \r\ntwo \r\nthree \r\n' my_list = [line.strip() for line in my_str.splitlines()] print(my_list) # 👉️ ['one', 'two', 'three']
We used a list comprehension. List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.
str.strip()
method to strip any leading and trailing whitespace from the string.If you get empty strings in the result and want to filter them out, use the
filter()
function.
my_str = '\r\none\r\ntwo\r\nthree\r\n' my_list = list(filter(None, my_str.splitlines())) print(my_list) # 👉️ ['one', 'two', 'three']
The filter function takes a function and an iterable as arguments and constructs an iterator from the elements of the iterable for which the function returns a truthy value.
None
for the function argument, all falsy elements of the iterable are removed.All values that are not truthy are considered falsy. The falsy values in Python are:
None
and False
.0
(zero) of any numeric type""
(empty string), ()
(empty tuple), []
(empty list), {}
(empty dictionary), set()
(empty set), range(0)
(empty
range).Note that the filter()
function returns a filter object (not a list). If you
need to convert the object to a list, pass it to the list()
class.