Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find index of first element not equal to a specific value

I want to find the index of the first element in a string that is not equal to a given value

Pseudo code:

string='111111234131986'
string.find(!='1')

Result:

6
like image 795
Riccardo La Marca Avatar asked Mar 03 '23 02:03

Riccardo La Marca


2 Answers

Here is a very simple solution using lstrip() and len():

len(string) - len(string.lstrip("1"))

This solution returns len(string) if string is empty or entirely composed by "1"s.

like image 149
Riccardo Bucco Avatar answered Mar 06 '23 09:03

Riccardo Bucco


Assuming you want the first element that isn't '1', we can use next() and enumerate()

>>> string='111111234131986'
>>> next((i for i, x in enumerate(string) if x!='1'), None)
6
like image 37
CDJB Avatar answered Mar 06 '23 09:03

CDJB