0

I want to search through a string and get the first index of any sub-string in a given set of sub-strings.

I tried 'word'.find('g' or 'r') and expected this to return the index: 2, but or does not work obviously.

How can I achieve this concisely?

Mohit Motwani
  • 4,662
  • 3
  • 17
  • 45
Karan
  • 25
  • 7
  • use regex `'g|r'` but with module `re` instead of command `find` – furas Apr 20 '20 at 11:14
  • 1
    Does this answer your question? [What's the most efficient way to find one of several substrings in Python?](https://stackoverflow.com/questions/842856/whats-the-most-efficient-way-to-find-one-of-several-substrings-in-python) – Georgy Apr 20 '20 at 12:03

1 Answers1

5

I think you can use re module here:

import re

re.search(r'[gr]', text).start()

In case you have separate substrings:

re.search(r'(foo)|(bar)', text).start()
Mohit Motwani
  • 4,662
  • 3
  • 17
  • 45