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.

Easy Python 3.9+ Aug 9, 2026 Strings & text 16 views 0 copies

Python code

23 lines
Python 3.9+
def 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

stdout
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

  1. Use `re.split(r'\s*,\s*', text)` to split on commas while ignoring surrounding whitespace in one step.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.