string manipulation
Python
split function
delimiters
programming basics

Split a string by a delimiter in Python

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Python makes delimiter-based splitting look easy, but real input usually has edge cases such as empty fields, repeated separators, or delimiters inside values. The right solution depends on the shape of the data, not just on the fact that a separator exists.

Use the Built-In String Methods First

For ordinary fixed-delimiter text, start with split. It is simple, readable, and fast.

python
text = "apple,banana,cherry"
parts = text.split(",")
print(parts)

If you only want one split from the left or right side, add maxsplit:

python
1config = "key=value=extra"
2print(config.split("=", 1))
3
4path = "folder/subfolder/file.txt"
5print(path.rsplit("/", 1))

Use partition when you need exactly one delimiter split and want to preserve whether the delimiter was present:

python
name = "host:api.example.com"
print(name.partition(":"))

Decide Whether Empty Fields Matter

Repeated delimiters create empty strings in the result. That behavior is sometimes correct and sometimes not.

python
raw = "a,,b,"
parts = raw.split(",")
print(parts)  # ['a', '', 'b', '']

If empty fields are meaningful, keep them. If they are noise, filter them intentionally:

python
cleaned = [item for item in raw.split(",") if item]
print(cleaned)

The key point is to let the input contract decide. A positional record format may need those empty fields preserved.

Normalize Whitespace After Splitting

Whitespace around delimiters is common in configuration files and user input. Split first, then trim each token.

python
1line = " host = api.example.com ; port = 443 ; secure = true "
2fields = [item.strip() for item in line.split(";") if item.strip()]
3
4result = {}
5for field in fields:
6    key, value = field.split("=", 1)
7    result[key.strip()] = value.strip()
8
9print(result)

This pattern is much safer than assuming the input is already clean.

Use the Right Tool for Complex Formats

If your delimiters vary, re.split can help:

python
1import re
2
3text = "a,b; c\td"
4parts = [item.strip() for item in re.split(r"[,;\t]", text) if item.strip()]
5print(parts)

If the data is actually CSV, do not use split(","). CSV allows quoted commas, which basic splitting cannot parse correctly.

python
1import csv
2from io import StringIO
3
4row = '101,"Doe, Jane",active'
5reader = csv.reader(StringIO(row))
6print(next(reader))

Choosing the correct parser early saves a lot of debugging later.

Validate the Parsed Output

Splitting text is only half the job. You should also validate token count and required values before using the result downstream.

python
1def parse_record(line: str) -> tuple[str, str, str]:
2    parts = line.split("|", 2)
3    if len(parts) != 3 or any(part == "" for part in parts):
4        raise ValueError(f"Invalid record: {line}")
5    return parts[0], parts[1], parts[2]
6
7
8print(parse_record("alice|admin|active"))

Validation keeps malformed input from silently entering business logic where it is harder to diagnose.

For code that parses external input repeatedly, wrap the split logic in a helper with one clearly documented contract. That keeps delimiter rules, whitespace policy, and validation in one place instead of scattering slightly different split calls across the codebase.

Common Pitfalls

  • Using split(",") on CSV data that contains quoted commas.
  • Removing empty tokens even though field positions matter.
  • Forgetting maxsplit and accidentally splitting more than intended.
  • Mixing parsing rules and business logic in one large function.
  • Accepting malformed token counts without raising an error.

Summary

  • Use split for straightforward fixed-delimiter parsing.
  • Use rsplit, partition, or maxsplit when only part of the string should be split.
  • Preserve or drop empty fields based on the actual data contract.
  • Reach for re.split or csv only when the input format truly requires them.
  • Validate parsed output immediately so bad input fails early.

Course illustration
Course illustration

All Rights Reserved.