【问题标题】:How to print() with python last two words form sentence with space如何用python打印()最后两个单词形成带空格的句子
【发布时间】:2020-08-30 23:56:51
【问题描述】:

如何用python print() 最后两个单词组成带空格的句子?像“Hello world,有 200 件”,我需要打印:“200 件”。非常感谢。

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"

【问题讨论】:

标签: python string split slice


【解决方案1】:

使用[-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

【讨论】:

  • 完美的 Gabip,谢谢
【解决方案2】:
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"

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-12
      • 1970-01-01
      • 2011-09-10
      • 2018-01-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多