How do I match the last occurence of a character?

Andrew M. Kuchling akuchlin at
Thu Jun 10 14:54:44 CEST 1999

Jeff P. writes:
>I've been messing with this for a little while now, but I can't get this
>to work. How do I match the last occurence of '\' in a string? I want to
>remove the file name from a url (e.g. news/breakingnews/981001b.html -->
>news/breakingnews/ ).

    Rather than using all the machinery of regular expressions, use
the string module: string.rfind(S, Ssub) returns the last occurrence
of Ssub in S:

>>> import string
>>> s='a/b/c/d'
>>> string.rfind(s, '/')
>>> s[5:]

A.M. Kuchling
The world is full of people whose notion of a satisfactory future is, in fact,
a return to an idealised past.
    -- Robertson Davies, _A Voice from the Attic_

More information about the Python-list mailing list