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?

Farhan.K
  • 3,425
  • 2
  • 15
  • 26
Kudrllr
  • 19
  • 2

4 Answers4

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
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
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
timgeb
  • 76,762
  • 20
  • 123
  • 145
0

Try this :

(i for i,c in enumerate(string) if c in symbol_list ).next()
timgeb
  • 76,762
  • 20
  • 123
  • 145
C.LECLERC
  • 510
  • 3
  • 12
0
pattern = re.compile('['+"".join(symbol_list)+']')
print string.index(pattern.search(string).group())
zxy
  • 148
  • 1
  • 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 Oct 08 '16 at 08:21
  • While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) 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 Oct 08 '16 at 10:16