Is there a simple way to start splitting a string from a certain point?

Viewed 100

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 Answers

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:].

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']
Related