Solving split string in python without the use of split() function

后端 未结 5 417
野趣味
野趣味 2021-01-15 20:59

Faced an interview question in Python that was as follow?

ex: 
input = (\'192.168.15.1\', \'.\', -1) ===> output = (192, 168, 15, 1)
input = (\'192.168.15         


        
5条回答
  •  心在旅途
    2021-01-15 21:26

    def split(text, sep, maxsplit=-1):
        parts = []
        end = -1
        while True:
            start = end + 1
            end = text.find(sep, start)
            if (end == -1) or (maxsplit == 0):
                parts.append(text[start:])
                break
            else:
                parts.append(text[start:end])
                if maxsplit != 0: maxsplit -= 1
        return parts
    
    print(split('192.168.15.1', '.', -1))  # ['192', '168', '15', '1']
    print(split('192.168.15.1', '.', 2))  # ['192', '168', '15.1']
    

提交回复
热议问题