Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string to list conversion in python?

Tags:

python

regex

I have a string like :

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

what I want is list :

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

What I have done is :

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 an optimized code in python 2.6 .

Thanks

like image 693
EMM Avatar asked Jan 19 '12 09:01

EMM


1 Answers

Use regular expressions:

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

This splits the string everywhere there's a space followed by one or more letters and a colon. The look-ahead ((?= part) makes it split on the whitespace while keeping the \w+: parts

like image 69
Dor Shemer Avatar answered Sep 23 '22 15:09

Dor Shemer