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

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

    another simpler and short approach is you can use regular expressions like this:

    import re
    def split_without_using_split_fn(s, c, i):
        if i<=0:
            print(re.findall("[^"+c+"]+(?=\\"+c+"|$)", s))
        else:
            l=re.findall("[^"+c+"]+(?=\\"+c+"|$)", s)
            print(l[0:-i]+[c.join(l[i:])])
    
    split_without_using_split_fn(*('192.168.15.1', '.', -1))
    split_without_using_split_fn(*('192.168.15.1', '.', 2))
    

    Output:

    $ python3 p.py 
    ['192', '168', '15', '1']
    ['192', '168', '15.1']
    $
    

提交回复
热议问题