splitlines()

splitlines(): split the string by using line breaks as delimiter
splitlines() returns a list after breaking a string using line breaks as delimiter
my_str='Welcome\n to\n Plus2net'
output=my_str.splitlines()
print(output)

my_str='Welcome\n to\n Plus2net'
output=my_str.splitlines(True)
print(output)
Output is here
['Welcome', ' to', ' Plus2net']
['Welcome\n', ' to\n', ' Plus2net']

Using keepends=True

The keepends=True parameter retains line break characters in the output:

my_str = "Line1\nLine2\r\nLine3"
output = my_str.splitlines(keepends=True)
print(output)  # Output: ['Line1\n', 'Line2\r\n', 'Line3']

Explanation: The line breaks \n and \r\n are retained in the output list when keepends is set to True.

Processing Log Data

When working with log files or multiline strings, `splitlines()` is useful for separating lines:

log_data = "Error1\nWarning1\r\nInfo1"
lines = log_data.splitlines()
for line in lines:
    print(line)  # Output: 'Error1', 'Warning1', 'Info1'

Explanation: This example processes log data line by line, making it easier to parse and analyze.

Handling Empty Strings

An empty string returns an empty list:

my_str = ""
output = my_str.splitlines()
print(output)  # Output: []

Explanation: If the input string is empty, `splitlines()` returns an empty list without errors.

All String methods


Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer