Kudrllr Kudrllr - 1 year ago 124
Python Question

Python - How to return the position in string where character matches from a list

I have a list:

symbol_list = ['/', '.', '\"', '-']

and a changing string which currently contains:

string = 'This is a string/ of "text"'

and I'm trying to find the most efficient way to return the index value where the first match from the list is made in the string. e.g. index value is
in above example.

Any advice please?

Answer Source

First, make your symbol list a set for O(1) containment checks. Then use a generator and get its first value. I recommend -1 as the fallback value.

>>> symbol_list = ['/', '.', '\"', '-']
>>> symbol_set = set(symbol_list)
>>> string = 'This is a string/ of "text"'
>>> idx = next((idx for idx, c in enumerate(string) if c in symbol_set), -1)
>>> idx
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download