String to convert list in python?

I have a line like:

searchString = "u:sads asdas asdsad n:sadasda as:adds sdasd dasd a:sed eee" 

what i want is a list:

 ["u:sads asdas asdsad","n:sadasda","as:adds sdasd dasd","a:sed eee"] 

What I've done:

 values = re.split('\s', searchString) mylist = [] word = '' for elem in values: if ':' in elem: if word: mylist.append(word) word = elem else: word = word + ' ' + elem list.append(word) return mylist 

But I want optimized code in python 2.6 .

thanks

+7
source share
2 answers

Use regular expressions:

 import re mylist= re.split('\s+(?=\w+:)', searchString) 

This breaks the line wherever there is a space followed by one or more letters and a colon. Looking ahead ( (?= Part) makes it split into spaces, preserving \w+: parts

+12
source

You can use the look ahead feature offered by many regex engines. Basically, regex engines test a pattern without consuming it when looking to the future.

 import re s = "u:sads asdas asdsad n:sadasda as:adds sdasd dasd a:sed eee" re.split(r'\s(?=[az]:)', s) 

This means that it splits only when we have \s followed by any letter and colon, but do not consume these tokens.

+1
source

All Articles