-2

As said in the official documentation, in Python when calling the function index on a String

index raises ValueError when x is not found in s

I know we can test the existence of a char in a String simply like this 'c' in String, but it makes the syntax kind of akward.

Is there any known implementation of the function index that would return a -1 or such an error code instead of raising an Error

jeremie
  • 971
  • 9
  • 19
  • That syntax is considered 'pythonic' because it leverages how the language functions and how it was written to be used. You can write logic to do it, but it is against the spirit of the language. (What I was told when I tried to break other functions and make them work like other languages) – dfundako Jun 27 '18 at 13:31
  • What do you consider "awkward" about the `in` keyword syntax? It's readable, concise and works. Beyond that, a quick look in the docs would have told you about `find()`. – Zinki Jun 27 '18 at 13:32
  • @Zinki, awkward is maybe a bit strong, but let's say that it makes your code a bit longer and forces you to check the content of the String twice (first, for the existence, second for the index finding). Agree with you, `find()` will do the job – jeremie Jun 27 '18 at 14:34

2 Answers2

2

The method you're looking for is str.find - even the documentation for str.index says it does the same except raising an error...

M. Volf
  • 1,259
  • 11
  • 29
1

Or use a generator expression with default value as -1:

print(next((i for i, x in enumerate(string) if x == search_value), -1))
Austin
  • 25,759
  • 4
  • 25
  • 48
  • Yes that's true, but I just wanted to avoid running the loop in python. I was hoping to find a function in C I could call. – jeremie Jun 27 '18 at 16:22