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