How to Partition a String on the First Delimiter in Python

Split a string into a tuple of (before, delimiter, after) at the first occurrence of a given delimiter, using a custom function or the built-in str.partition.

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

Python code

26 lines
Python 3.9+
def partition_string(s, delimiter):
    """Split string into (before, delimiter, after) on the first occurrence."""
    for i, ch in enumerate(s):
        if ch == delimiter:
            return s[:i], ch, s[i+1:]
    return s, "", ""


if __name__ == "__main__":
    # Single-character delimiter
    s1 = "hello,world,how,are,you"
    print(partition_string(s1, ","))

    # Multi-character delimiter
    s2 = "first---second---third"
    delim = "---"
    idx = s2.find(delim)
    if idx != -1:
        result = (s2[:idx], delim, s2[idx+len(delim):])
    else:
        result = (s2, "", "")
    print(result)

    # No delimiter found
    s3 = "no-delimiter-here"
    print(partition_string(s3, "-"))

Output

stdout
('hello', ',', 'world,how,are,you')
('first', '---', 'second---third')
('no', '-', 'delimiter-here')

How it works

The custom partition_string function iterates through the string character by character until it finds the delimiter, then returns the slices before and after using string slicing. If the delimiter is never found, it returns the original string with empty strings for the delimiter and the rest. For multi-character delimiters, using str.find and slicing with idx + len(delim) is more efficient than scanning each character. Python's built-in str.partition does exactly this job more cleanly and supports multi-character separators, returning the same three-tuple. The example demonstrates both approaches to show the logic and the practical alternative.

Common mistakes

  • Using `split` and rejoining, which loses the actual delimiter and only splits one way.
  • Forgetting to handle the case where the delimiter is not present, causing IndexError or wrong output.
  • Using `find` with a single character but not accounting for multi-character delimiters in string length.

Variations

  1. Use the built-in `str.partition(delimiter)` which handles all delimiter lengths and returns the same tuple.
  2. Use `re.split` with a capture group to keep the delimiter but only for simple patterns.

Real-world use cases

  • Parsing header lines in text files where the first colon separates the key from the value.
  • Extracting the protocol and path from a URL by partitioning on the first '://'.
  • Splitting log lines at the first space to separate the timestamp from the message.

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.