
Python's splitlines() Method
Do you have a long text that you'd like to chop up into a series of lines? Python has got you covered with its splitlines() method. It's a super-useful tool that transforms a string into a list of separate lines. Here's how it works:
string.splitlines()
This handy method is just the ticket for objects of the String type.
The role of splitlines() is to slice a string into individual lines each time it stumbles upon a line break character. These characters might look like \n (which represents a newline) or \r\n (a carriage return followed by a newline).
By its nature, splitlines() leaves out line break characters when it does its slicing and dicing. But suppose you want them included in the split? No problem! Just specify keepends=True as a parameter within the parentheses.
Let's walk through a quick example to show how the splitlines() function works in practice.
First, let's assign a string to the variable "text". We'll include the special characters "\n" and "\r".
text = "Hello everyone!\nWelcome to the Python tutorial.\r\nHappy coding!"
Next, we'll call upon the splitlines() method to chop up the string into a neat list of lines. We'll assign this result to our "lines" variable.
lines = text.splitlines()
Now, let's check out what we've got. We can print out the content of the "lines" variable.
print(lines)
You'll see that the method has neatly divided the text into a list of strings. It's used the line break characters \r and \n as dividers.
['Hello everyone!', 'Welcome to the Python tutorial.', 'Happy coding!']
However, the separator characters \r and \n are missing from the list.
Want them back in? Just specify the keepends=True attribute within the parentheses.
For example, let's call the splitlines method once more, this time with the keepends attribute.
lines = text.splitlines(keepends=True)
Now let's print out the content of the "lines" variable again.
print(lines)
This time, you'll notice the method has kept the separator characters \n and \r in the list.
['Hello everyone!\n', 'Welcome to the Python tutorial.\r\n', 'Happy coding!']