Locate a Substring's Position

Easy ⏱ 8 min 76% acceptance ★★★★☆ 4.2
Write find_position(s, sub) that returns the index of the first occurrence of sub in s, or -1 if sub does not appear at all.

Examples

Example 1
Input
s = 'hello world', sub = 'world'
Output
6
Explanation

'world' starts at index 6.

Example 2
Input
s = 'hello world', sub = 'xyz'
Output
-1
Explanation

No match found.

Constraints

  • sub may be empty (in which case a valid implementation returns 0).

Topics

StringsSubstring Search

Companies

JPMorgan ChaseDeutsche Bank

Hints

Hint 1

`str.find()` does exactly this and returns -1 on failure (unlike `str.index()`, which raises).

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.