The split() method in Python divides a string into a list of substrings based on a specified separator, returning that list. By default, it splits on any whitespace (spaces, tabs, newlines) and removes empty strings, so "hello world".split() returns ['hello', 'world'].
How split() Works Under the Hood
When you call string.split(separator, maxsplit), Python scans the string from left to right, looking for the separator. Each time it finds the separator, it cuts the string at that point and adds the piece before it to the result list. The separator itself is not included in the output. If no separator is given, Python treats any sequence of whitespace characters as a single delimiter and ignores leading or trailing whitespace.
For example:
text = "apple,banana,cherry"
print(text.split(",")) # ['apple', 'banana', 'cherry']
The method always returns a list, even if the string contains no separator—in that case, the list has one element: the original string. An empty string "".split() returns [], not [''], because there is nothing to split.
The maxsplit Parameter: Controlling How Many Splits
The optional maxsplit argument limits the number of splits performed. If you set maxsplit=2, Python splits only the first two occurrences of the separator, and the remainder of the string becomes the last element of the list. This is useful when you only care about the first few fields and want to keep the rest intact.
data = "2024-05-01-weather-report"
print(data.split("-", 2)) # ['2024', '05', '01-weather-report']
If maxsplit is negative or omitted, there is no limit—Python splits on every occurrence. Note that maxsplit counts the number of separators, not the number of resulting pieces; the list length is always maxsplit + 1 when the separator appears at least that many times.
Choosing the Right Separator
The separator can be any string, not just a single character. Common choices include commas for CSV data, newlines for line-by-line processing, or custom delimiters like "::". When dealing with CSV files, be careful: a simple split(",") breaks if a field contains a comma inside quotes. For robust CSV parsing, use Python’s built-in csv module instead.
- Whitespace default:
"a b".split()→['a', 'b'](multiple spaces collapse) - Explicit single space:
"a b".split(" ")→['a', '', 'b'](empty string for the double space) - Newline split:
"line1\nline2".split("\n")→['line1', 'line2']
If your separator appears at the start or end of the string, split() includes an empty string in the result. For example, ",a,b".split(",") returns ['', 'a', 'b']. This is often unexpected, so you may need to filter out empty strings with a list comprehension or use strip() first.
Common Mistakes and Pitfalls
One frequent mistake is confusing split() with split(" "). The former treats any whitespace (including tabs and multiple spaces) as one delimiter, while the latter only splits on literal spaces and preserves empty strings. This can cause bugs when reading files with inconsistent spacing.
Another issue is splitting on a regex pattern. split() does not accept regular expressions—it only takes a literal string. If you need to split on multiple different delimiters, such as commas or semicolons, use the re.split() function from the re module instead:
import re
print(re.split(r"[,;]", "a,b;c")) # ['a', 'b', 'c']
Also remember that split() works only on strings, not on lists or other iterables. If you try to split a list, you’ll get an AttributeError. For splitting a list into chunks, use slicing or itertools.
split() vs. partition() and rsplit()
Python offers related methods that behave differently. partition(sep) returns a tuple of three elements: the part before the separator, the separator itself, and the part after it. It only splits once, and if the separator is not found, it returns the original string followed by two empty strings. This is handy when you need to keep the delimiter.
rsplit() works like split() but scans from the right. It is useful when you want to split off the last few fields, such as extracting a file extension: "archive.tar.gz".rsplit(".", 1) → ['archive.tar', 'gz']. The maxsplit parameter counts from the right side.
For splitting a string into exactly two parts at the first occurrence, partition() is often clearer than split(sep, 1) because it returns the separator too, which can be useful for reassembly.
Performance and Memory Considerations
For most use cases, split() is fast and efficient. However, splitting a very large string (hundreds of megabytes) creates a list that holds all the substrings in memory at once. If you only need to process each piece one at a time, consider using splitlines() for newline-separated text, or iterate over the string with a generator expression to avoid building the entire list. The str.splitlines() method handles different line endings (\n, \r\n, \r) automatically.
When splitting on a single character that appears frequently, the operation is O(n) in the string length. If you are repeatedly splitting the same string with different separators, it may be more efficient to use re.split() with a compiled pattern, especially if the pattern is complex.
Frequently Asked Questions
Does split() modify the original string? No. Strings are immutable in Python, so split() returns a new list and leaves the original string unchanged. If you need to keep the result, assign it to a variable.
How do I split a string into characters? Use list("hello") or "hello".split("")—but the latter raises a ValueError because an empty separator is not allowed. The correct way is list("hello") which gives ['h', 'e', 'l', 'l', 'o'].
What is the difference between split() and splitlines()? splitlines() splits on line boundaries (\n, \r\n, \r, and a few Unicode line separators) and by default removes the line break characters. split("\n") only splits on literal newlines and leaves them out, but it does not handle \r\n on Windows files correctly unless you normalize first.
Can I split a string into a dictionary? Not directly. You can split into a list and then use slicing or zip() to pair keys and values. For example, dict(["a=1".split("=")]) works, but only for a single pair. For multiple pairs, use a loop or a dictionary comprehension.
Why does split() return an empty list for an empty string? Because there are no substrings to extract. If you need [''] as a result, you can check for an empty string first and handle it separately, or use ["".join(string)].
Related
- Oracle String to Value: Converting Text in SQL
- Snowflake String Contains: SQL Methods and Examples
- Print String and Int on Arduino
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel NPV of a Series of Cash Flows: Formula and ExamplesTo calculate the net present value of a cash-flow series in Excel, use =NPV(B1,B3:B5)+B2 when the discount rate…
- Excel Day of Week from Date: Formulas and FormattingIf your date is in A2, enter =TEXT(A2,"dddd") to show its full weekday name; for example, an actual…
- Excel INDEX MATCH Examples and How to Use ThemIn Excel, INDEX MATCH looks up a value by finding its position with MATCH and returning the value…
- Excel Formula to Convert Minutes to HoursTo convert a number of minutes in cell A2 to decimal hours in Microsoft Excel, divide by 60:…
- How to Rank in Excel: Formulas, Ties, and Sorting DataYes, Excel can rank numbers with the RANK.EQ function. If the scores are in B2:B5, enter =RANK.EQ(B2,$B$2:$B$5,0) in…
- IFERROR Formula in Excel: Syntax, Examples, and FixesIn Excel, use IFERROR to return a chosen result when a formula produces an error: it has the…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.