python - Create function to split on seperators -
this function takes in 2 arguments, text , separators both strings , returns list of non-empty, non-blank strings text, determined splitting text on of separators. separators string of single-character separators.
here example:
def split_on_separators(text, separators) >>>split_on_separators("hooray! finally, we're done.", "!,") ['hooray', ' finally', " we're done."]
this have far:
location_of_sep = [] result = [] in range(len(text)): if original[i] in separators: location_of_sep.append(i)
i'm stuck after part. have location of separator, how can add together list result. tried following:
location_of_sep= [6, 15] #location of separator illustration given above j in location_of_sep: result.append(text[0:j])
this not work because not text between 2 separators. may on thinking this. help appreciated
how using re.split
:
>>> import re >>> re.split("[!,]", "hooray! finally, we're done.") ['hooray', ' finally', " we're done."]
if don't want utilize regular expression:
using zip
, can create pairs.
>>> text = "hooray! finally, we're done." >>> location_of_sep = [6, 15] >>> zip([-1] + location_of_sep, location_of_sep + [none]) [(-1, 6), (6, 15), (15, none)] >>> [(i+1,j) i, j in zip([-1] + location_of_sep, location_of_sep + [none])] [(0, 6), (7, 15), (16, none)] >>> [text[i+1:j] i, j in zip([-1] + location_of_sep, location_of_sep + [none])] ['hooray', ' finally', " we're done."]
python string python-3.x
No comments:
Post a Comment