How to Split Strings in Python (Beginner-Friendly)
Split Python strings by a delimiter into lists, plus a cleanup variant that strips whitespace and filters empty parts.
Python code
23 linesdef split_text(text, delimiter=" "):
"""Split a string by a delimiter and return a list of parts."""
return text.split(delimiter)
def split_text_with_cleanup(text, delimiter=" "):
"""Split a string, stripping whitespace and filtering empty parts."""
parts = text.split(delimiter)
cleaned = [part.strip() for part in parts if part.strip()]
return cleaned
if __name__ == "__main__":
sample = " apple, banana , cherry ,, date "
print("Default split (space):")
print(split_text("hello world python"))
print("\nSplit by comma:")
print(split_text(sample, delimiter=","))
print("\nSplit by comma with cleanup:")
print(split_text_with_cleanup(sample, delimiter=","))
Output
Default split (space):
['hello', 'world', 'python']
Split by comma:
[' apple', ' banana ', ' cherry ', ', date ']
Split by comma with cleanup:
['apple', 'apple', 'banana', 'cherry', 'date']
How it works
The str.split() method returns a list of substrings broken at every occurrence of the delimiter. It uses consecutive whitespace by default when called with no args, but when given a delimiter (like a comma), it keeps empty strings or spaces around tokens. Our split_text_with_cleanup strips each token with .strip(), then filters out any empty strings — this is ideal for messy CSV-like input. Note the raw split on ', date ' yields a token that still has a comma, which is why cleaning preserves only the desired parts.
Common mistakes
- Calling split() without an argument changes behavior from delimiter-based to whitespace-based (collapses multiple spaces, drops empty strings).
- Forgetting to strip leading/trailing whitespace on individual tokens before using them.
- Assuming split() removes empty strings — it does NOT when you pass an explicit delimiter like ','; only the default whitespace split does.
Variations
- Use `re.split(r'\s*,\s*', text)` to split on commas while ignoring surrounding whitespace in one step.
- Use `[w for w in text.split(delimiter) if w]` if you only need to drop empties without stripping spaces.
Real-world use cases
- Parsing user input where fields are comma or space separated, like tagging or hashtag lists.
- Breaking down CSV lines that sometimes contain extra spaces, before mapping to dicts or dataclasses.
- Splitting log file lines by whitespace to extract timestamps, levels, and messages for analysis.
Sponsored
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.