Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何用python打印()最后两个单词构成带空格的句子_Python_String_Split_Slice - Fatal编程技术网

如何用python打印()最后两个单词构成带空格的句子

如何用python打印()最后两个单词构成带空格的句子,python,string,split,slice,Python,String,Split,Slice,如何用python打印()最后两个单词构成带空格的句子?比如“你好,世界上有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:]切片分割的句子将返回所需的输出。尝试

如何用python打印()最后两个单词构成带空格的句子?比如“你好,世界上有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

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

这是因为您在索引-3中打印了列表,您应该从末尾到索引-3使用所有元素,这样您就可以使用前面提到的:运算符。这是因为您在索引-3中打印了列表,您应该从末尾到索引-3使用所有元素,这样您就可以使用前面提到的:运算符[-3:?这没有意义:
我需要什么[-3]
它计算到右边的第三个单词,但是你放弃了结果,所以它没有效果。这回答了你的问题吗?这回答了你的问题吗?
我需要什么[-3:
?这没有意义:
我需要什么[-3]
它的计算结果是右边第三个单词,但您放弃了结果,因此它没有任何效果。这回答了您的问题吗?这回答了您的问题吗?完美加比普,谢谢完美加比普,谢谢
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"