Reputation: 9054
How would I find the first occurrence of either the character e
or o
?
I want to do something like this:
my_string = "Hello World"
x = my_string.find('e' or 'o',my_string)
print x # 1
Upvotes: 2
Views: 1315
Reputation: 19733
you can use collections.defaultdict
:
>>> import collections
>>> my_dict = collections.defaultdict(list)
>>> for i,x in enumerate("hello world"):
... if x in "eo":
... my_dict[x].append(i)
...
>>> my_dict
defaultdict(<type 'list'>, {'e': [1], 'o': [4, 7]})
>>> my_dict['e'][0] # 1st 'e'
1
>>> my_dict['o'][0] # 1st 'o'
4
Upvotes: 0
Reputation:
Alternatively, you could do a find
on each character and then take the minimum of all the results (throwing away the -1
s unless all of them are -1
):
def first_index(string, search_chars):
finds = [string.find(c) for c in search_chars]
finds = [x for x in finds if x >= 0]
if finds:
return min(finds)
else:
return -1
This yields:
>>> first_index("Hello World", "eo")
1
>>> first_index("Hello World", "xyz")
-1
Upvotes: 0
Reputation: 239443
Use enumerate
function with a generator expression, like this
>>> next(idx for idx, char in enumerate("Hello World") if char in 'eo')
1
It will give the index of the first character which is either e
or o
.
Note: It will fail if the characters are not there in the string. So, you can optionally pass the default value, like this
>>> next((idx for idx, char in enumerate("Hello World") if char in 'eo'), None)
1
>>> next((idx for idx, char in enumerate("Hi") if char in 'eo'), None)
None
Upvotes: 1