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

后端 未结 5 405
野趣味
野趣味 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:05

    You could solve this task with following function

    def split_string(istr,ich,inte):
        res = []
        prev = 0
        for i,ch in enumerate(istr):
            if ch == ich:
                res.append(istr[prev:i])
                prev = i+1
                inte = inte-1
                if inte == 0:
                    break            
        if prev < len(istr):
            res.append(istr[prev:])
        return res
    

    or another solution

    def split_string(istr,ich,inte):
        res = []
        h,_,r = istr.partition(ich)
        while r:
            res.append(h)
            inte = inte-1
            if inte == 0:
                h = r
                break               
            h,_,r = r.partition(ich)
        if h:
            res.append(h)
        return res
    

    For following code

    print split_string('192.168.15.1', '.', -1)
    print split_string('192.168.15.1', '.', 2)
    

    output will be

    ['192', '168', '15', '1']
    ['192', '168', '15.1']
    

提交回复
热议问题