0

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 16 in above example.

Any advice please?

0

4 Answers 4

1

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
16
1
  • Works perfectly, thank you.
    – Kudrllr
    Commented Oct 7, 2016 at 14:08
1

You can iterate over the (index, character) pairs with enumerate(), and use a set for fast lookup:

>>> def get_pos(s):
...     for i, c in enumerate(s):
...         if c in {'/', '.', '\"', '-'}:
...             return i
... 
>>> s = 'This is a string/ of "text"'
>>> get_pos(s)
16
1
  • Also works perfectly, thank you too.
    – Kudrllr
    Commented Oct 7, 2016 at 14:08
0
pattern = re.compile('['+"".join(symbol_list)+']')
print string.index(pattern.search(string).group())
2
  • 1
    We welcome answers that help the OP to understand the solution. Your answer would be improved by adding context and explanation.
    – James K
    Commented Oct 8, 2016 at 8:21
  • While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
    – andreas
    Commented Oct 8, 2016 at 10:16
0

Try this :

(i for i,c in enumerate(string) if c in symbol_list ).next()
1
  • That is specifically for Python 2
    – idjaw
    Commented Oct 7, 2016 at 14:07

Not the answer you're looking for? Browse other questions tagged or ask your own question.