Created
June 10, 2012 19:49
-
-
Save shazow/2907110 to your computer and use it in GitHub Desktop.
split_first
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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