Splitting of string at an interval
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sun Apr 7 17:48:07 EDT 2013
On Sun, 07 Apr 2013 13:25:57 -0700, subhabangalore wrote:
> Dear Group,
>
> I was looking to split a string in a particular interval, like,
>
> If I have a string,
> string="The Sun rises in the east of our earth"
>
> I like to see it as,
> words=["The Sun","rises in","in the","east of","our earth"]
>
> If any one of the learned members can kindly suggest.
Like every programming problem, the solution is to break it apart into
small, simple steps that even a computer can follow.
1) Split the string into words at whitespace.
words = string.split()
2) Search for the word "in", and if found, duplicate it.
tmp = []
for word in words:
if word == 'in':
tmp.append('in')
tmp.append(word)
words = tmp
3) Take the words two at a time.
phrases = [words[i:i+2] for i in range(0, len(words), 2)]
4) Join the phrases into strings.
phrases = [' '.join(phrase) for phrase in phrases]
--
Steven
More information about the Python-list
mailing list