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']
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.
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.
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 methodsAuthor
🎥 Join me live on YouTubePassionate 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.