Idiom for "last word in a string"

Christos Trochalakis yatiohi at ideopolis.gr
Wed Sep 23 21:17:12 CEST 2009


At Wed, 23 Sep 2009 18:47:05 +0000 (UTC),
Grant Edwards wrote:
> 
> I recently ran across this construct for grabbing the last
> (whitespace delimited) word in a string:
> 
>    s.rsplit(None,1)[1]
> 
> It was somewhat obvious from the context what it was supposed
> to do, but it took a bit of Googling to figure out exactly what
> was going on.
> 
> When I want the last word in a string, I've always done this:
> 
>    s.split()[-1]
> 
> I was wondering what the advantage of the rsplit(None,1)[1]
> approach would be other than inducing people to learn about the
> maxsplit argument that is accepted by the split() methods?
> 

s.rsplit(None, 1) is a cheaper operation because it splits the string
*only once*.



More information about the Python-list mailing list