Skip to content
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

NameDescription
subThe text to look for.
startOptional starting position.
endOptional 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 ValueError or use in before calling if the substring presence is uncertain.

Related entries