Splitting Strings
Concepts covered: Splitting & Joining
.split() divides a string into a list of substrings based on a delimiter. By default, it splits on whitespace (spaces, tabs, newlines).
sentence = "Python is a powerful language"
words = sentence.split()
print(words)
print(len(words))Output:
['Python', 'is', 'a', 'powerful', 'language'] 5
This produces ['Python', 'is', 'a', 'powerful', 'language'] with 5 elements. The split() method returns a list.
Splitting on a custom delimiter
Pass a delimiter string to split on specific characters:
csv_line = "apple,banana,cherry,date"
fruits = csv_line.split(",")
print(fruits)
path = "/home/user/documents/file.txt"
parts = path.split("/")
print(parts)Output:
['apple', 'banana', 'cherry', 'date'] ['', 'home', 'user', 'documents', 'file.txt']
The first split produces ['apple', 'banana', 'cherry', 'date']. The path split produces ['', 'home', 'user', 'documents', 'file.txt']; the empty string at the start comes from the leading slash.
Limiting splits
The optional maxsplit parameter limits how many splits occur:
log_line = "ERROR:2024-01-15:Database connection failed: timeout"
parts = log_line.split(":", 2)
print(parts)Output:
['ERROR', '2024-01-15', 'Database connection failed: timeout']
This splits only at the first 2 colons, producing ['ERROR', '2024-01-15', 'Database connection failed: timeout']. The message with colons stays intact.
Splitting with splitlines()
.splitlines() splits on line boundaries, handling different line ending conventions (\n, \r\n, \r):
text = """Line 1
Line 2
Line 3"""
lines = text.splitlines()
print(lines)
print(len(lines))Output:
['Line 1', 'Line 2', 'Line 3'] 3
This produces ['Line 1', 'Line 2', 'Line 3'] with 3 elements. Unlike split('\n'), splitlines() handles all line ending types correctly.
The split() and join() methods are complementary: split() turns a string into a list, and join() turns a list back into a string. Together they form the split-transform-join pattern, which is one of the most common string processing idioms in Python.
Calling split() without arguments splits on any whitespace and discards empty strings caused by consecutive spaces. Calling split(" ") splits only on single spaces and preserves empty strings between adjacent spaces.
About this lesson
This section is part of the Strings: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.