What are other ways to split a string without using the split() method? For example, how could [\'This is a Sentence\'] be split into [\'This\', \'is\', \'a\', \'Sentence\']
A recursive version, breaking out the steps in detail:
def my_split(s, sep=' '):
s = s.lstrip(sep)
if sep in s:
pos = s.index(sep)
found = s[:pos]
remainder = my_split(s[pos+1:])
remainder.insert(0, found)
return remainder
else:
return [s]
print my_split("This is a sentence")
Or, the short, one-line form:
def my_split(s, sep=' '):
return [s[:s.index(sep)]] + my_split(s[s.index(sep)+1:]) if sep in s else [s]
sentence = 'This is a sentence'
word=""
for w in sentence :
if w.isalpha():
word=word+w
elif not w.isalpha():
print(word)
word=""
print(word)