searching backwards in a string

Stefan Schwarzer s.schwarzer at
Tue Feb 12 12:58:25 EST 2002

Hello Mark

"Mark Zöltsch" wrote:
> > Short answer:  Reverse the string first.
> I'm new to this python stuff and to this newsgroup too..

Welcome to Python :-)

> but why you don't use 'rfind' instead of 'find'?
> I think that's much easier...
> somthing like:
> import string
> str = 'ac ab ab ac'
> res = string.rfind(str, 'ac', 0, len(str))
> print 'last position :', res

string.rfind works, as the module name suggests, with constant strings.
However, Paul asked for a search of a _regular expression pattern_
which is not possible with rfind.

I think the answer from Steve is the most appropriate for the question.

Btw, I would recommend to use rfind as string method:

example_string = 'ac ab ab ac'
result = example_string.rfind('ac')

Two more notes:

- str might be a bad name because it's the name for the string type in
  Python 2.2:

  >>> s = 'abc'
  >>> type(s)
  <type 'str'>

  Naming an object str would also make it impossible to use the builtin
  str as factory:
  >>> str(1)
  >>> str = 'abc'
  >>> str(1)
  Traceback (most recent call last):
    File "<stdin>", line 1, in ?
  TypeError: 'str' object is not callable

  (unless you qualify it explicitly:

  >>> __builtins__.str(1)

  which can probably be considered to be bad style. ;-) )

- You can omit 0 and len(str) because these are the defaults anyway.


More information about the Python-list mailing list