Python String splitlines
Now, we are going to learn about the splitlines method. With this method, we get a list of the lines in the string, breaking at the line boundaries. We can also provide another argument, which is keepends, and if keepends argument is specified as True, then the line breaks are also included in the resulting list. Let’s have a look at a simple program, which demonstrates the same thing.
Python String splitlines() Method
As you can see in the above program, we have a string, and then we are trying to call the splitlines method. In the string, we can see that we have some newlines inserted, and we are going to get a list of lines in the string. Since we have not specified the second argument keepends, the line breaks are not included in the list. Let’s have a look at the output of the program.
[‘Hello’, ‘From’, ‘GyaniPandit’]
As you can see in the output, we got the list of strings, with the strings split at the line breaks. Now, Let’s say that we specify the keepends argument as True, and in such a situation, we would have the line breaks included in the list.
Let’s have a look at a simple example, which tries to demonstrate the same thing.
As you can see in the above program, we have a simple string again, and then we are using the splitlines method. This time, we have specified the keepends argument as True, and in such a case, we can find that the line breaks are included in the resulting list. Let’s have a look at the output now.
[‘Hello\n’, ‘From\n’, ‘GyaniPandit’]
As you can see in the output, we have the line breaks included in the list. So, as and when required, we can make use of the splitlines method, which returns a list of lines in the string, breaking at some line boundaries. We can consider different line boundaries, like \n, \r, \f, and others. Also, we can specify another argument keepends as True, due to which, the line breaks will be included in the resulting list.