Skip to content

Instantly share code, notes, and snippets.

@shazow
Created June 10, 2012 19:49
Show Gist options
  • Save shazow/2907110 to your computer and use it in GitHub Desktop.
Save shazow/2907110 to your computer and use it in GitHub Desktop.
split_first
class TestUtil(TestCase):
def test_split_first(self):
test_cases = [
(
('abcd', ['b']),
('a', 'cd')
),
(
('abcd', ['c', 'b']),
('a', 'cd')),
(
('abcd', []),
('abcd', '')
),
]
for input, expected in test_cases:
output = split_first(*input)
self.assertEqual(output, expected)
def split_first(s, delims):
"""
Given a string and an iterable of delimiters, split on the first found
delimiter. Return two split parts.
If not found, then the first part is the full input string.
"""
min_idx = None
for d in delims:
idx = s.find(d)
if idx < 0:
continue
if not min_idx:
min_idx = idx
else:
min_idx = min(idx, min_idx)
if min_idx < 0:
return s, ''
return s[:min_idx], s[min_idx+1:]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment