亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何用python打印()最后兩個詞用空格形成句子

如何用python打印()最后兩個詞用空格形成句子

搖曳的薔薇 2022-11-18 16:41:46
如何用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


查看完整回答
反對 回復 2022-11-18
?
紫衣仙女

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"


查看完整回答
反對 回復 2022-11-18
?
慕勒3428872

TA貢獻1848條經驗 獲得超6個贊

這是因為您在索引 -3 中打印了列表,您應該從末尾到索引 -3 獲取所有元素,這樣您就可以像之前提到的那樣使用 : 運算符



查看完整回答
反對 回復 2022-11-18
  • 3 回答
  • 0 關注
  • 152 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號