为了账号安全,请及时绑定邮箱和手机立即绑定

如何用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条经验 获得超5个赞

这是因为您在索引 -3 中打印了列表,您应该从末尾到索引 -3 获取所有元素,这样您就可以像之前提到的那样使用 : 运算符



查看完整回答
反对 回复 2022-11-18
  • 3 回答
  • 0 关注
  • 96 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信