how to get the first 5 words from a string in python

Last updated 3 weeks, 5 days ago | 32 views 75     5

Tags:- Python

Python | Get the first 5 words from a string

This can be done by using the `split()` and `join()` methods

>>> massage = 'Today is a sunny day but tomorrow it might rain'
>>> five_words = ' '.join(massage.split()[:5])
>>> five_words
'Today is a sunny day'

The `.split()` method used to split the string into a list that allows extracting words from the string, list slice operation `[:5]` provide the first five words from the list string, and finally `.join()` method is used to join the extracted words together to create a new string