The split() method in Python breaks a string into a list of substrings based on a separator (delimiter) you specify. By default, it splits on whitespace (spaces, tabs, newlines) and returns a list of words. You can also set a maximum number of splits. This is one of the most used string methods for parsing text, reading CSV lines, or cleaning user input.
What You'll Need
- Python 3 installed (any recent version works; the method is identical in Python 2.7 but we focus on Python 3 here).
- A text editor or IDE (like VS Code, PyCharm, or even a simple notepad).
- A Python interpreter or a terminal/command prompt to run your script.
Step-by-Step
- Start with a string variable. For example:
text = "apple,banana,cherry". This will be the string you want to split. - Call the
split()method on the string. Writetext.split()to split on whitespace by default. For our example, because there are no spaces, it would return["apple,banana,cherry"]— a list with one item. To split on commas, usetext.split(","). - Store the result in a variable. Example:
fruits = text.split(","). Nowfruitsis a list:['apple', 'banana', 'cherry']. - Use the
maxsplitparameter (optional). Add a second argument to limit the number of splits. For instance,text.split(",", 1)splits only at the first comma, giving['apple', 'banana,cherry']. The rest of the string stays intact as the last element. - Handle multiple whitespace characters. If your string has extra spaces or tabs,
split()with no arguments collapses all whitespace and removes empty strings. Example:"a b\tc".split()returns['a', 'b', 'c']. - Split on newlines. Use
splitlines()for line breaks, orsplit("\n")to split on newline characters. Note thatsplitlines()handles different line endings (like\r\n) better. - Test with a real-world example. Try parsing a simple CSV line:
line = "John,Doe,35,New York"thenfields = line.split(",")gives['John', 'Doe', '35', 'New York'].
Common Mistakes
- Forgetting the separator. If you call
split()on a string like"a,b,c", you get['a,b,c']because it splits on spaces, not commas. Always specify the delimiter if it's not whitespace. - Assuming the result is a string.
split()always returns a list. If you need a string back, you'll have to join it withjoin(). - Using
split()on a non-string. If you try123.split(), you'll get anAttributeError. Convert numbers to strings first:str(123).split(). - Ignoring empty strings. When splitting on a character that appears consecutively (like
"a,,b".split(",")), you get['a', '', 'b']. This is correct behavior, but it often surprises beginners. - Using
split()on a string with leading/trailing whitespace. Without arguments,split()handles it fine, but if you specify a separator like" ", you'll get empty strings at the ends.
Tips
- Use
split()without arguments for most text cleaning tasks — it automatically handles multiple spaces and tabs. - If you only need the first few parts, set
maxsplitto avoid processing the whole string, which can be more efficient for large texts. - Combine
split()withstrip()to remove extra whitespace from each piece:[item.strip() for item in data.split(",")]. - For CSV files, consider the
csvmodule if your data has quoted fields or commas inside quotes —split()is too simple for that. - Remember that
split()returns a list, so you can iterate over it directly:for word in sentence.split():.
Troubleshooting
If your split doesn't give the expected result:
- Check the separator. Print the string to see exactly what characters are there (like hidden tabs or newlines). Use
repr()to display them:print(repr(my_string)). - Check for empty strings. If you see empty items, decide if you want to filter them out with a list comprehension: .
- If you get an error like
AttributeError: 'int' object has no attribute 'split', you're trying to split a number. Convert it to a string first. - If the string is very large and split is slow, consider using
re.split()for complex patterns, or adjust your approach to avoid splitting the whole string if you only need a part. - If you're working with multiline text and want to split on line breaks, use
splitlines()instead ofsplit("\n")because it handles different newline characters correctly.
Frequently Asked Questions
What does split() return if the string is empty?
It returns an empty list: "".split() gives []. If you specify a separator, like "".split(","), it also returns [].
Can I split on multiple different characters at once?
No, split() only takes one separator. To split on multiple delimiters, use the re.split() function from the re module, e.g., re.split(r"[,;]", text) splits on commas or semicolons.
How do I get the last part of a split string?
Use negative indexing: text.split(",")[-1] gives the last element. Or use rsplit() to split from the right: text.rsplit(",", 1)[-1].
What's the difference between split() and partition()?
split() returns a list of all parts. partition() splits at the first occurrence and returns a tuple of three items: (before, separator, after). For example, "a,b,c".partition(",") gives ('a', ',', 'b,c').
Does split() modify the original string?
No, strings are immutable in Python. split() returns a new list; the original string remains unchanged.
How do I split a string into characters?
Use list() instead: list("hello") gives ['h', 'e', 'l', 'l', 'o']. Or use split() with an empty separator, but that raises a ValueError. So list() is the correct way.