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.
Python code
26 linesdef 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
('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
- Use the built-in `str.partition(delimiter)` which handles all delimiter lengths and returns the same tuple.
- 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
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.