如何从字符串中获取一组单词?

时间:2017-10-30 03:07:01

标签: python indexing split slice

我有一个句子的字符串。句子中有八个单词。我试图做的是将第三个,第四个和第五个单词作为句子。我尝试过使用索引,例如:

string[3][4][5]

但这会引发IndexError。我在这里缺少什么?

2 个答案:

答案 0 :(得分:2)

# 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]

或者,如果您只需要第三个和第五个字,请使用thead_list[2]thead_list[4]

如果您需要连接提取的结果单词,请执行以下操作:

new_title = " ".join(words) # converts ["word1", "word2"] to "word1 word2"

将上述所有步骤合并为一行代码:

thead = " ".join(page_soup.title.string.split()[3:6])

答案 1 :(得分:0)

你可以试试这个:

thead = page_soup.title.string
final_word1, final_word2 = thead.split()[2], thead.split()[4]