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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With