I have a string that is a sentence. There are eight words in the sentence. What I'm trying to do, is take the third, forth, and fifth word the sentence. I have tried using indexing such as:
string[3][4][5]
But this raises an IndexError
. What am I missing here?
# split the title string into words (split by spaces)
thead_list = page_soup.title.string.split()
# access elements with index 3, 4, 5
words = thead_list[3:6]
Or if you want just the third and fifth words, use thead_list[2]
and thead_list[4]
If you need to concatenate the resulting words that you extracted, then do this:
new_title = " ".join(words) # converts ["word1", "word2"] to "word1 word2"
Combining all of the above steps into one line of code:
thead = " ".join(page_soup.title.string.split()[3:6])
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments