Python – Split string with space delimiter

Python – Split string with space delimiter

Use re.split():

import re
re.split(( ),Im a test)

This gives :

[Im,  , 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+),Im    a test)
#[Im,     , a,  , test]

Try :

list =  Im a test.split()

Python split string by default by spaces.

The output will be:

list = [Im,a,test]

Its mean that you need only add space element between each element in list.


temp_list=  Im a test.split()
list= []
for i in temp_list:
list = list[:-1]

Python – Split string with space delimiter

Leave a Reply

Your email address will not be published.