如何使用python最后两个单词用空格形成句子的print()



如何使用python最后两个单词用空格形成句子的print((?就像"你好世界,有 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"

[-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_words
sentence = "Hello world, there is 200 pcs"
lastThreeWords = get_last_n_words(3, sentence)
# lasthreeWords: "is 200 pcs"

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

最新更新