Extract first 3 words from string
13,449
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'
Comments
-
Tarjo almost 2 years
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'