3 回答

TA貢獻(xiàn)1817條經(jīng)驗(yàn) 獲得超14個(gè)贊
將拆分后的句子切片[-2:]將返回所需的輸出。嘗試:
sentence = "Hello world, there is 200 pcs"
what_I_need = sentence.split()
print(what_I_need[-2:]) # output: ['200', 'pcs']
# or as a string:
print(" ".join(what_I_need[-2:])) # output: 200 pcs

TA貢獻(xiàn)1839條經(jīng)驗(yàn) 獲得超15個(gè)贊
def get_last_n_words(n:int, sentence:string):
last_n_Words = ' '.join(sentence.split()[-n:])
return last_n_words
sentence = "Hello world, there is 200 pcs"
lastThreeWords = get_last_n_words(3, sentence)
# lasthreeWords: "is 200 pcs"

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超6個(gè)贊
這是因?yàn)槟谒饕?-3 中打印了列表,您應(yīng)該從末尾到索引 -3 獲取所有元素,這樣您就可以像之前提到的那樣使用 : 運(yùn)算符
添加回答
舉報(bào)