searching backwards in a string
s.schwarzer at ndh.net
Tue Feb 12 18:58:25 CET 2002
"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
>>> s = 'abc'
Naming an object str would also make it impossible to use the builtin
str as factory:
>>> str = 'abc'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'str' object is not callable
(unless you qualify it explicitly:
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