TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Your Ultimate Guide to Python String Find()
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python BasicPython Tutorials

Your Ultimate Guide to Python String Find()

Last updated: Oct 28, 2023 10:02 pm
By Meenakshi Agarwal
Share
7 Min Read
Python String Find with Examples
Python String Find with Examples
SHARE

This tutorial explains the Python string find() method that searches a substring and returns the index of its first occurrence. If not successful, then it returns the status as (-1). Let’s try to understand its usage with the help of simple examples.

Contents
String Find() SyntaxParametersReturn ValuesFind() ExamplesFind() function with default valuesThe string contains two or more substringsWhen find() doesn’t find a substringFind() string with begin and end indices

1. Find() syntax
2. Find() with default values
3. Find() with multiple occurrences of substrings
4. Find() when no substrings exist
5. Find() with start and end indices

Let’s now go through each of the sections one by one.

Python String Find() with Examples

String’s find() is a built-in Python function that finds a substring in another string that contains it. If successful, it returns the index of the first match. Otherwise, the function returns a (-1) to mark the failure.

Let’s now see the details and check out how can we use it.

String Find() Syntax

The basic syntax to use Python string find() is as follows:

Given_string.find(Sub_string, Begin_index, End_index)

Parameters

Below are the descriptions of the parameters in the above function.

  • Given_string: It is the string object that we’ve to traverse.
  • Sub_string: It is the substring argument that we want to find.
  • Begin_index: It is the starting index to begin the search in our input string. It is an optional parameter. And, if we don’t specify it, then find() takes zero as the default.
  • End_index: It tells the find() function where to end the search. It is also an optional argument. And, if we don’t specify it, then the highest index number becomes the default.

Return Values

The find() function may have one of the following return values.

  • If the string contains the substring, then the return value is the index of the first occurrence.
  • If the substring doesn’t match, then the return value is -1.

Note:- The first occurrence is the lowest index when the substring occurs twice or more times in the source string.

Also Read: Python String Strip

Find() Examples

Here, we are using string find() to address different use cases in Python. Hope, these should help you with this function from all corners.

Find() function with default values

In this example, we’ve not passed any values in the find() call. So, it will assume the default values for beginning and ending indices.

As stated initially, the default for begin_index is 0, and for end_index is the length of the string.

"""
 Desc:
  Python example to demonstrate string find() function
"""

in_str = 'Does Python supports Lambda function?'
find_str = 'supports'

ret_index = in_str.find(find_str)

print(f"The input string: {in_str}")
print(f"The position of '{find_str}' substring is: ", ret_index)

After executing the above snippet, you will see this result:

The input string: Does Python supports Lambda function?
The position of 'supports' substring is: 12

We’ve used Python f-string in all examples given here. Hence, make sure you run these using Python 3.6.

The string contains two or more substrings

As stated earlier, the string find() returns the first index in case of multiple occurrences of a substring. Here’s an example to see this behavior:

"""
 Desc:
  Using find() when the string has two or more occurrences of a substring
"""

in_str = 'The most popular Python versions are Python 2.6, and Python 3.6.'
find_str = 'Python'

ret_index = in_str.find(find_str)

print(f"The input string is: {in_str}")
print(f"The position of '{find_str}' substring is: {ret_index}")

This code would give you the following result:

The input string is: The most popular Python versions are Python 2.6, and Python 3.6.
The position of 'Python' substring is: 17

Also Check: Python Ord() Function All You Need to Know

When find() doesn’t find a substring

Let’s understand – what does Python find() returns when the given string doesn’t contain the required substring? Usually, in this case, the function should fail and return -1. Here’s an example to observe this behavior:

"""
Desc:
Using find() when the string doesn't contain the substring
"""

in_str = 'The most popular Python versions are Python 2.6, and Python 3.6.'
find_str = 'CSharp'

ret_index = in_str.find(find_str)

print(f"The input string is: {in_str}")
print(f"The position of '{find_str}' substring is: {ret_index}")

After running this code, you will get the following output:

The input string is: The most popular Python versions are Python 2.6, and Python 3.6.
The position of 'CSharp' substring is: -1

Find() string with begin and end indices

When you supply the two optional arguments of the find() method. Then, it searches the substring in a particular range, i.e., between (start, end).

Let’s see how to use the starting and ending indices with the find() function. The below example demonstrates how to find a substring within a string in Python.

"""
Desc:
Using str.find(str, start, end) to find substring in sliced string
"""

in_str = 'The most popular Python versions are Python 2.6, and Python 3.6.'
find_str = 'Python'

start = in_str.find(find_str) + len(find_str)
end = len(in_str)

ret_index = in_str.find(find_str, start, end)

print(f"The input string is: {in_str}")
print(f"The position of '{find_str}' in sliced string '{in_str[start:end]}' is: {ret_index}")

In this Python string example, we tried to find the index of the second occurrence of our substring. That’s why we found the first index and incremented it by the substring’s length. After running the given snippet, you should see the following result:

The input string is: The most popular Python versions are Python 2.6, and Python 3.6.
The position of 'Python' in sliced string ' versions are Python 2.6, and Python 3.6.' is: 37

Congratulations! You finally completed this tutorial successfully.

We hope you now feel confident using the Python string find() method to find substrings in strings. Be sure to check out our other tutorial on concatenating strings in Python.

Also, to learn Python from scratch to depth, read our step-by-step Python tutorial.

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article MySQL Insert to Add Single Multiple Rows MySQL Insert Statement to Add Rows
Next Article Generate random numbers list in Python Generate a List of Random Integers in Python

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x