4

Let's say I have this string 'This is an example hello'

Which if split would become ['This', 'is', 'an', 'example', 'hello']

If I wanted to only take the last three words and put them in a list, to get ['an', 'example', 'hello'] is there a simple way to do that?

An idea would of course be to split the whole sentence then just remove the first elements but I was wondering if there was some other method I was missing to directly get the same result. Thank you in advance.

PS: This is my first question asked here, I'm sorry if it's not perfect, please point out what might be wrong so I can improve next times! :)

2 Answers2

4

Try this

string = 'This is an example hello'

split = string.split()[-3:]

Because we know that split string returns a list, we can get the last 3 elements of the list using [-3:].

Dharman
  • 30,962
  • 25
  • 85
  • 135
The Pilot Dude
  • 2,091
  • 2
  • 6
  • 24
2

Use str.rsplit with its optional maxsplit argument. And Use * operator to pack it into a list:

>>> string = 'This is an example hello'
>>> first_part, *last_three = string.rsplit(sep=' ', maxsplit=3)

>>> first_part
'This is'

>>> last_three
['an', 'example', 'hello']
Sayandip Dutta
  • 15,602
  • 4
  • 23
  • 52