Splitting strings in Python without split()

后端 未结 8 713
醉话见心
醉话见心 2021-01-17 03:59

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\']

相关标签:
8条回答
  • 2021-01-17 04:37

    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]
    
    0 讨论(0)
  • 2021-01-17 04:38
    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)
    
    0 讨论(0)
提交回复
热议问题