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
Something like this would work:
def splitter(string_, splitchar, maxsplits):
# if maxsplits is positive, split string into maxsplits of parts, on splitchar.
# Otherwise perform as many splits as the string allows.
out = []
sub = []
for ch in string_:
if ch != splitchar:
sub.append(ch)
else:
if maxsplits < 1 or (maxsplits > 0 and (len(out) < maxsplits)):
out.append(''.join(sub))
sub = []
else:
sub.append(ch)
out.append(''.join(sub))
return tuple(out)
>>> splitter.splitter('192.168.15.1', '.', -1)
('192', '168', '15', '1')
>>> splitter.splitter('192.168.15.1', '.', 2)
('192', '168', '15.1')
>>> splitter.splitter('192.168.15.1', '.', 0)
('192', '168', '15', '1')
>>> splitter.splitter('192.168.15.1', '.', 1)
('192', '168.15.1')