How to Use String find() Method in PythonPython Basics


The find() method returns the index of first occurrence of the substring (if found). If not found, it returns -1.

Example

#!/usr/bin/python3
# -*- coding: UTF-8 -*-

str = "Associate professor in computer science and also a joint professor in information science"

# From the beginning, found the 1st occurrence
print (str.find('professor'))

# For the index of 30 and after, found the 2nd occurrence
print (str.find('professor', 30))

# For the index of 60 and after, not found and return -1
print (str.find('professor', 60))

Output:

10
57
-1

Syntax

str.find(substr[, start[, end]] )

Parameters

Name Description
substr The substring to be searched in the string

Return Value

It returns the index if found and -1 otherwise.

© 2024 Cheerlearn.com, all rights reserved. Privacy Policy | Contact Us