4

Is there any efficient way to select the last characters of a string until there's a whitespace in Python?

For example I have the following string:

str = 'Hello my name is John'

I want to return 'John'. But if the str was:

str = 'Hello my name is Sally'

I want to retrun 'Sally'

Paolo
  • 351
  • 2
  • 4
  • 12

3 Answers3

26

Just split the string on whitespace, and get the last element of the array. Or use rsplit() to start splitting from end:

>>> st = 'Hello my name is John'
>>> st.rsplit(' ', 1)
['Hello my name is', 'John']
>>> 
>>> st.rsplit(' ', 1)[1]
'John'

The 2nd argument specifies the number of split to do. Since you just want last element, we just need to split once.

As specified in comments, you can just pass None as 1st argument, in which case the default delimiter which is whitespace will be used:

>>> st.rsplit(None, 1)[-1]
'John'

Using -1 as index is safe, in case there is no whitespace in your string.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • 1
    You can use `None` instead of `' '`. – Ashwini Chaudhary Oct 10 '13 at 18:31
  • Explicit is better than implicit! I believe `' '` is definitely the only advisable way to `rsplit` the string. – hexparrot Oct 10 '13 at 19:12
  • @hexparrot Except that `None` splits at any whitespace (space, \t, \n...) character, while `' '` only at spaces. The question was actually whitespaces, so None is a more accurate answer... – Nearoo Feb 13 '20 at 09:05
3

It really depends what you mean by efficient, but the simplest (efficient use of programmer time) way I can think of is:

str.split()[-1]

This fails for empty strings, so you'll want to check that.

MJ Howard
  • 111
  • 5
2

I think this is what you want:

str[str.rfind(' ')+1:]

this creates a substring from str starting at the character after the right-most-found-space, and up until the last character.

This works for all strings - empty or otherwise (unless it's not a string object, e.g. a None object would throw an error)

mgoldwasser
  • 14,558
  • 15
  • 79
  • 103