Splitting strings in Python without split()

后端 未结 8 795
醉话见心
醉话见心 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:27

    string1 = 'bella ciao amigos'
    split_list = []
    tmp = ''
    for s in string1:
       if s == ' ':
           split_list.append(tmp)
           tmp = ''
       else:
           tmp += s
    if tmp:
       split_list.append(tmp)
    
    print(split_list)
    

    Output: ------> ['bella', 'ciao', 'amigos']

    reverse_list = split_list[::-1]
    print(reverse_list)
    

    Output: ------> ['amigos', 'ciao', 'bella']

提交回复
热议问题