Вы могли бы сделать метод пользовательского разделения:
class Str(str):
def split(self, sep=None, maxsplit=-1):
if sep is not None and len(sep) != 1:
return NotImplemented # Can't figure out how to do seps longer than 1...
whole = []
curr = []
for i in self:
if i not in (sep or "\n \t"):
curr.append(i)
elif curr != []:
whole.append("".join(curr))
curr = []
whole.append("".join(curr))
if sep is None:
whole = [i for i in whole if i != ""]
if maxsplit > -1:
whole[maxsplit:] = ["".join(whole[maxsplit])]
return whole
Затем используйте это нравится:
my_str = Str("Hello, How are you, List Item here, Index blah, Gonna split")
print(my_str.split())
# Output:
['Hello,', 'How', 'are', 'you,', 'List', 'Item', 'here,', 'Index', 'blah,', 'Gonna', 'split']
Вы может сделать это функцией, если не является классом:
def split(str_to_split, sep=None, max_split=-1):
if sep is not None and len(sep) != 1:
return NotImplemented
whole = []
curr = []
for i in str_to_split:
if i not in (sep or "\n \t"):
curr.append(i)
elif curr != []:
whole.append("".join(curr))
curr = []
whole.append("".join(curr))
if sep is None:
whole = [i for i in whole if i != ""]
if maxsplit > -1:
whole[maxsplit:] = ["".join(whole[maxsplit])]
return whole
Посмотрите на http://codereview.stackexchange.com/questions/47627/is-this-a-good-implementation-of-the-split-функцию для разных способов реализации 'split' :) –