Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to split at NEWLINEs in Python?
In Python, splitting strings at newlines is a common text processing task. Python provides two main approaches: the splitlines() method and the split() method with '\n' parameter.
Using splitlines() Method
The splitlines() method is specifically designed for splitting strings at line breaks. It handles various types of line endings automatically and doesn't require any parameters ?
Example 1
Splitting a string with escape sequence newlines ?
text = "Welcome\nto\nTutorialspoint"
print("The given string is:")
print(text)
print("\nThe resultant string split at newline is:")
print(text.splitlines())
The given string is: Welcome to Tutorialspoint The resultant string split at newline is: ['Welcome', 'to', 'Tutorialspoint']
Example 2
Splitting a multi-line string using triple quotes ?
text = """Welcome
To
Tutorialspoint"""
print("The given string is:")
print(text)
print("\nThe resultant string split at newline is:")
print(text.splitlines())
The given string is: Welcome To Tutorialspoint The resultant string split at newline is: ['Welcome', 'To', 'Tutorialspoint']
Using split() Method
The split() method is more general-purpose and can split at any specified character. To split at newlines, pass '\n' as the parameter ?
Example 1
Using split('\n') to divide the string at newlines ?
text = "Welcome\nto\nTutorialspoint"
print("The given string is:")
print(text)
print("\nThe resultant string split at newline is:")
print(text.split('\n'))
The given string is: Welcome to Tutorialspoint The resultant string split at newline is: ['Welcome', 'to', 'Tutorialspoint']
Example 2
Splitting a multi-line string with split('\n') ?
text = """Welcome
To
Tutorialspoint"""
print("The given string is:")
print(text)
print("\nThe resultant string split at newline is:")
print(text.split('\n'))
The given string is: Welcome To Tutorialspoint The resultant string split at newline is: ['Welcome', 'To', 'Tutorialspoint']
Comparison
| Method | Parameters | Line Ending Types | Best For |
|---|---|---|---|
splitlines() |
None required | All types (\n, \r\n, \r) | Cross-platform text processing |
split('\n') |
Separator required | Only \n | Simple Unix-style line breaks |
Conclusion
Use splitlines() for robust line splitting that handles different line ending formats. Use split('\n') when you specifically need to split only at Unix-style newlines.
