简体   繁体   中英

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'

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM