2

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
2
  • its not clear, you want 1st occurance of both e or o, OR you want only any one?? Commented Feb 2, 2015 at 4:01
  • 2
    It's fairly clear. The first sentence literally reads "How would I find the first occurrence of either the character e or o?" Commented Feb 2, 2015 at 4:22

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

What's the use of next ?
@AvinashRaj The argument passed to enumerate is called a generator expression. It is like a normal function, but it can return values whenever you ask for the next value from it, till it exhausts.
0

Alternatively, you could do a find on each character and then take the minimum of all the results (throwing away the -1s 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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.