String Methods
index()
Find the first position of some text and raise an error if it is missing.
str.index(sub, start=0, end=len(str))
str.index() is like str.find(), but raises a ValueError when the substring is not found instead of returning -1.
Parameters
| Name | Description |
|---|---|
| sub | The text to look for. |
| start | Optional starting position. |
| end | Optional position where the search stops. |
Returns
The first index where the text occurs.
Try it
Run it and change it
text = "banana"
print(text.index("na"))
Worth knowing
- Exception safety: Wrap in
try...except ValueErroror useinbefore calling if the substring presence is uncertain.