Karan
Karan

Reputation: 25

Find index of first matching substring

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?

Upvotes: 0

Views: 98

Answers (1)

Mohit Motwani
Mohit Motwani

Reputation: 4792

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()

Upvotes: 5

Related Questions