如何用python最后兩個單詞打?。ǎ┬纬蓭Э崭竦木渥??比如“Hello world, there are 200 pcs”,我需要打印:“200 pcs”。太感謝了。sentence = "Hello world, there is 200 pcs"what_I_need = sentence.split()what_I_need[-3]# That prints "is"print(what_I_need)# But I need to print "is 200 pcs"
3 回答

大話西游666
TA貢獻1817條經驗 獲得超14個贊
將拆分后的句子切片[-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貢獻1839條經驗 獲得超15個贊
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"
添加回答
舉報
0/150
提交
取消