Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 16624

Implement a function that works the same as str.split method (without using str.split itself, of course)

$
0
0

I tried a code that works for some of the splits. But it keeps failing on the majority of asserts. Can u plese help?

from typing import List

def split(data: str, sep=None, maxsplit=-1):    empty_str = ""    my_list = []    for c in data:        if c[0] == ',':            my_list.append(c)        elif c == '' and empty_str != '':            my_list.append(empty_str)            empty_str = ''        else:            empty_str += c    if maxsplit == 0:        return data    if empty_str:        my_list.append(empty_str)    return my_listif __name__ == '__main__':    assert split('') == []    assert split(',123,', sep=',') == ['', '123', '']    assert split('test') == ['test']    assert split('Python    2     3', maxsplit=1) == ['Python', '2     3']    assert split('    test     6    7', maxsplit=1) == ['test', '6    7']    assert split('    Hi     8    9', maxsplit=0) == ['Hi     8    9']    assert split('    set   3     4') == ['set', '3', '4']    assert split('set;:23', sep=';:', maxsplit=0) == ['set;:23']    assert split('set;:;:23', sep=';:', maxsplit=2) == ['set', '', '23']

Viewing all articles
Browse latest Browse all 16624

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>