Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
python3
communitycreator

What is the String find() method in Python?

Maria Elijah

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The find() method finds the first occurrence of a given substring in a string.

Syntax

string_name.find(str, start, end)

string_name is the name of the string.

Parameter

str: Required. It specifies the substring to be searched.

start: Optional. It specifies where to begin the search. Default is 0.

end: Optional. It specifies where to end the search. Default is to the end of the string.

Return type

The find() method returns the index if found. Otherwise, it returns -1.

Code

The following code shows how to use the find() method in Python:

Example 1: Using find() without a start and end argument.


string = 'Educative shot'
  
# returns first occurrence of Substring
result = string.find('shot')
print ("Substring 'shot' is found at index:", result )
  
result = string.find('ca')
print ("Substring 'ca ' is found at index:", result )
  
# Using find() in conditional statement
if (string.find('Edu') != -1):
    print ("The string contains the given substring ")
else:
    print ("The string doesn't contains the given substring")

Example 2: Using find() with a start and end argument.


string = 'Educative shot'
  
# starts search at index 6 and ends at the last index by default
print(string.find('shot', 6)) 
  
# starts search at index 3 and ends at index 9
print(string.find('tive', 3, 9)) 
  
# starts search at index 1 and ends at index 7
print(string.find('ca ', 1, 7)) 

RELATED TAGS

python
python3
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring