1

I have put multiple strings in a list with the line.split(":") method and one of them contains a certain character I want to find and return its index in the list.

For example:

s = "Hello StackOverflow!"
lst = s.split(" ") # ["Hello", "StackOverflow!"]

Now I want to get the index of character '!', so the desired output should be index 1, as it's in the second string. I could not make it work with lst.find('!'), as it works only for characters in list and not strings in lists. Probably you can help find a simple solution.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Coder
  • 75
  • 6

1 Answers1

2
idx = next((i for i, word in enumerate(s.split()) if search_string in word), None)

To handle StopIteration explicitly, instead of silently returning None, remove the second parameter from the statement and use a try/except block:

try:
    idx = next(i for i, word in enumerate(s.split()) if search_string in word)
except StopIteration:
    ... # do something
Marat
  • 15,215
  • 2
  • 39
  • 48
  • 1
    Why `None`? I'd rather let the error propagate, myself, and I think that's better practice to show beginners. – wjandrea Aug 03 '23 at 20:10
  • Also, minor thing, but why `s.split()` instead of `lst`? – wjandrea Aug 03 '23 at 20:12
  • 1
    @wjandrea That's just one way to handle it. Which one is better depends on the outside context, which is missing in the question. – Marat Aug 03 '23 at 20:12
  • 1
    @wjandrea this is why I originally posted it as a comment - giving a rough idea without actually making a commitment to make it perfect – Marat Aug 03 '23 at 20:14
  • 2
    I'm not saying it has to be perfect, just that any assumptions should be mentioned in the answer, like for example *"If the character is not found, normally it'll raise `StopIteration`, but I put `None` as a default instead."* By all means edit that in if you want. – wjandrea Aug 03 '23 at 20:17