0

Wondering if there is a neat API in Python to search a string from backward (from a specific position in a string), for example, in string "Hello StackOverflow Hello Python", suppose I want to find the index of sub-string "Hello" which is previous to sub-string "Python"?

thanks in advance, Lin

4
  • 1
    Downvoted. First result for "python string" search gives you docs.python.org/2/library/string.html#string.rfind Commented Feb 27, 2016 at 1:29
  • @viraptor, nice catch. I am confused by rindex and rfind, which one is for my problem? Thanks. Commented Feb 27, 2016 at 1:45
  • 1
    Either one. The question is - do you want an exception thrown (rindex) or -1 returned (rfind) if the strings are missing. Commented Feb 27, 2016 at 1:49
  • @viraptor, I just need to get -1 when there is no hit, whether Exception is returned or not is not important, your recommendations are highly appreciated. :) Commented Feb 27, 2016 at 1:55

1 Answer 1

3

Yes, it's called str.rindex(). It takes arguments sub - a substring to look for, start - a starting position, and end.

It is the reverse of the index function. There are some others, like rsplit, too.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks Austin, always good to learn from you. Just to clarify, do you mean using rindex or using rfind? :)
That's up to you. Do you want a ValueError? But for your information, the index and rindex functions appear in a lot of languages, so they're a good pair to remember.
Hi Austin, I just need to get -1 when there is no hit, whether ValueError is returned or not is not important, your recommendations are highly appreciated. :)
Thanks for all the help, Austin. Mark your reply as answered.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.