如何用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
提交
取消