Splitting strings in Python without split()

后端 未结 8 772
醉话见心
醉话见心 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]
    

提交回复
热议问题