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
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']