Created
November 10, 2015 14:46
-
-
Save bencharb/7488a5b593b8f8c4222a to your computer and use it in GitHub Desktop.
split many
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_many(astring, *split_on_chars, **kwargs): | |
| """ | |
| Split a string on many values. | |
| :param split_on_chars: string to split | |
| :type split_on_chars: basestring | |
| :param split_on_chars: chars to split on | |
| :type split_on_chars: tuple | |
| :param kwargs: keep_empty: keeps empty strings in result, which happens with two adjacent separators in a string | |
| :type kwargs: dict | |
| """ | |
| keep_empty = kwargs.get('keep_empty') or False | |
| split_all = kwargs.get('split_all') or False | |
| lenchars = len(split_on_chars) | |
| if not lenchars: | |
| split_on_chars = (' ',) | |
| if lenchars == 1: | |
| result = astring.split(split_on_chars[0]) | |
| else: | |
| lastchar = split_on_chars[-1] | |
| result = reduce(lambda st, ch: st.replace(ch,lastchar), split_on_chars[:-1], astring).split(lastchar) | |
| if not keep_empty: | |
| result = filter(lambda x: x is not '', result) | |
| return result | |
| def test_split_many(): | |
| thestr = 'a_string with.many:_separators. ' | |
| split_chars = [' ',':', ',', '_', '.'] | |
| try: | |
| expected = ['a', 'string', 'with', 'many', 'separators'] | |
| assert expected == split_many(thestr, *split_chars) | |
| expected = ['a_string', 'with.many:_separators.'] | |
| assert expected == split_many(thestr) | |
| expected = ['a', 'string', 'with', 'many', 'separators'] | |
| assert expected == split_many(thestr, *split_chars) | |
| expected = ['a', 'string', 'with', 'many', '', 'separators', '', ''] | |
| assert expected == split_many(thestr, *split_chars, keep_empty=True) | |
| except AssertionError: | |
| print 'test failed' | |
| raise | |
| else: | |
| print 'test passed' | |
| # test_split_many() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment