Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract first 3 words from string

I am looking for a script code to search for the first 3 words of a string.

Example :

words = 'I am confused looking for 3 words from the front'

Expected results:

'I am confused'
like image 380
Tarjo Avatar asked Aug 25 '17 12:08

Tarjo


1 Answers

You can split the string into a list using the .split() method. Once you've done this you can extract the first 3 words from the sentence using a list slice ([:3]). Finally you'll want to join the result back together into a new string using .join():

words = 'I am confused looking for 3 words from the front'
' '.join(words.split()[:3])
>> 'I am confused'
like image 97
AK47 Avatar answered Sep 29 '22 17:09

AK47