-4

I'm currently working on a Python project and I would like to know how to split string with space delimiter. For example,

"I'm a test" would be ["I'm", "", "a", "", "test"]. So if anyone know how to do it, please help me.

Have a good day !

GamingActivity
  • 25
  • 1
  • 1
  • 5
  • `"I'm a test".split()` would get you pretty close and seems like a good starting point. (It won't preserve the delimiters though.) – NPE May 13 '18 at 13:07
  • @NPE Yes I know that, it is the first thing I tried but it doesn't keep space delimiter and I need it for what I'm making. – GamingActivity May 13 '18 at 13:08
  • 1
    [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers) – wwii May 13 '18 at 13:19
  • @GamingActivity where is your [mcve]? – Andy K May 13 '18 at 14:13

2 Answers2

7

Use re.split():

import re
re.split("( )","I'm a test")

This gives :

["I'm", ' ', 'a', ' ', 'test']

split works this way : (from the documentation) Split string by the occurrences of pattern. If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list.

So here since the space was places inside the capturing parenthesis, it was also returned as a part of the list.

EDIT : If the string had multiple spaces, and you do not want individual spaces to be separate elements of the list, use : (suggested by @NPE)

re.split("(\s+)","I'm    a test")
#["I'm", '    ', 'a', ' ', 'test']
Sruthi V
  • 2,623
  • 1
  • 9
  • 22
  • Nice answer, but please explain how this works (in particular, the significance of the capturing group). Also, please consider replacing `( )` with `(\s+)`. Thanks! – NPE May 13 '18 at 13:16
  • @NPE added it ! – Sruthi V May 13 '18 at 13:20
2

Try :

list =  'Im a test'.split()

Python split string by default by spaces.

The output will be:

list = ['Im','a','test']

It's mean that you need only add space element between each element in list.

Edit:

temp_list=  'Im a test'.split()
list= []
for i in temp_list:
    list.append(i)
    list.append('')
list = list[:-1]
Idan Str
  • 634
  • 1
  • 13
  • 31