如何用python打印()最后两个词用空格形成句子

如何用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"


摇曳的蔷薇
浏览 103回答 3
3回答

大话西游666

将拆分后的句子切片[-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

紫衣仙女

def get_last_n_words(n:int, sentence:string):   last_n_Words = ' '.join(sentence.split()[-n:])   return last_n_wordssentence = "Hello world, there is 200 pcs"lastThreeWords = get_last_n_words(3, sentence)# lasthreeWords: "is 200 pcs"

慕勒3428872

这是因为您在索引 -3 中打印了列表,您应该从末尾到索引 -3 获取所有元素,这样您就可以像之前提到的那样使用 : 运算符
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python