vendredi 8 août 2014

python - différence entre Rechercher et index - Stack Overflow


I am new to python and cannot quite understand the difference between find and index.


>>> line
'hi, this is ABC oh my god!!'
>>> line.find("o")
16
>>> line.index("o")
16

They always return the same result. Thanks!!




str.find returns -1 when it does not find the substring.


>>> line = 'hi, this is ABC oh my god!!'
>>> line.find('?')
-1

While str.index raises ValueError:


>>> line.index('?')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found



You can read this website to know how to implement find and index function.


You can find the two function using the same common function, just the return result is different.



I am new to python and cannot quite understand the difference between find and index.


>>> line
'hi, this is ABC oh my god!!'
>>> line.find("o")
16
>>> line.index("o")
16

They always return the same result. Thanks!!



str.find returns -1 when it does not find the substring.


>>> line = 'hi, this is ABC oh my god!!'
>>> line.find('?')
-1

While str.index raises ValueError:


>>> line.index('?')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found


You can read this website to know how to implement find and index function.


You can find the two function using the same common function, just the return result is different.


0 commentaires:

Enregistrer un commentaire