不使用split()函数,自己动手定义一个函数实现类似的基本功能,代码如下:
# -*- coding:utf8 -*-
def self_split(string, sep=' '):
if len(sep) > 1:
raise ValueError(f'sep must be of length 1, got {len(sep)}.')
lst = [0, ]
i = 0
while True:
try:
if string[i] != sep:
i += 1
continue
if string[i] == sep:
lst.append(i - 1)
i += 1
while string[i] == sep:
i += 1
lst.append(i)
except IndexError:
break
lst.append(len(string) - 1)
# print(lst)
start = []
stop = []
for idx, val in enumerate(lst):
if idx % 2 != 0:
stop.append(val)
else:
start.append(val)
s_lst = []
for st, sp in zip(start, stop):
if sp < 0:
continue
else:
s_lst.append(string[st:sp + 1])
return s_lst