How to write my own split function without using .split and .strip function?

  • A+
Category:Languages

How to write my own split function? I just think I should remove spaces, '/t' and '/n'. But because of the shortage of knowledge, I have no idea of doing this question

Here is the original question:

Write a function split(string) that returns a list of words in the given string. Words may be separated by one or more spaces ' ' , tabs '/t' or newline characters '/n' .

And there are examples:

words = split('duff_beer 4.00') # ['duff_beer', '4.00'] words = split('a b c/n') # ['a', 'b', 'c'] words = split('/tx y /n z ') # ['x', 'y', 'z'] 

Restrictions: Don't use the str.split method! Don't use the str.strip method

 


I think using regular expressions is your best option as well.

I would try something like this:

import re def split(string):     return re.findall('/S+',string) 

This should return a list of all none whitespace characters in your string.

Example output:

>>> split('duff_beer 4.00') ['duff_beer', '4.00'] >>> split('a b c/n') ['a', 'b', 'c'] >>> split('/tx y /n z ') ['x', 'y', 'z'] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: