0

How to print() with python last two words form sentence with space? Like "Hello world, there is 200 pcs", I need print: "200 pcs". Thank you so much.

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"
Gabio
  • 9,126
  • 3
  • 12
  • 32
M_Cas
  • 33
  • 1
  • 5
  • 2
    `what_I_need[-3:]`? – Tomerikoo May 14 '20 at 12:38
  • This doesn't make sense: `what_I_need[-3]` It evaluates to the third word from the right, but you are discarding the result so it has no effect. – Tom Karzes May 14 '20 at 12:39
  • Does this answer your question? [Understanding slice notation](https://stackoverflow.com/questions/509211/understanding-slice-notation) – Tomerikoo May 14 '20 at 12:40
  • Does this answer your question? [How can I tell python to take the last 2 words from an email that is in a list like structure but is not a list defined by python because it changes?](https://stackoverflow.com/questions/13482586/how-can-i-tell-python-to-take-the-last-2-words-from-an-email-that-is-in-a-list-l) – 0buz May 14 '20 at 12:40

3 Answers3

2

Slicing your splitted sentence with [-2:] will return the desired output. Try:

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
Gabio
  • 9,126
  • 3
  • 12
  • 32
1
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"
Viktor1903
  • 359
  • 1
  • 4
  • 18
0

this is because that you printed the list in index -3 you should take all element from the end till index -3 so you can use the : operator as mention before

Daniel Haish
  • 140
  • 9