EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials Python String Tutorial Python Find String
Secondary Sidebar
Python Tutorial
  • Sorting
    • Sorting in Python
    • Sorting Algorithms in Python
    • Bubble Sort in Python
    • Merge Sort in Python
    • Heap Sort in Python
    • Quick Sort in Python
    • Python Sorted Function
    • Sort string in Python
    • Insertion sort in Python
    • Shell sort in Python
    • Bucket Sort Python
    • Python Input String
    • Python String Operations
    • Python String Join
    • Python String Contains
    • Byte to String Python
    • Python Stream
    • Python List to String
    • Python String Replace
    • Python Compare Strings
    • Lowercase in Python
    • Python Split String
    • Python Multiline String
    • Python Find String
    • Python Trim String
    • Python Test Empty String
    • Python Slice String
    • Python Regex
    • Python Regex Tester
    • Python regex replace
  • Basics Part I
    • Introduction To Python
    • What Is Python
    • Print Statement in Python
    • Careers in Python
    • Advantages of Python
    • Uses of Python
    • Python SQL Server
    • Python SQL Database
    • Python SQL Server Connection
    • Python SQL Injection
    • Python Features
    • Heap Data Structure Python
    • Python Fast And python psyco
    • Python ImportError
    • Python Recursion
    • Python Reduce
    • Local Variable in Python
    • Sparse Matrix in Python
    • Benefits and Limitations of Using Python
    • What can I do with?Python
    • Is Python a scripting language
    • clock() in Python
    • Is Python Object Oriented
    • Is Python Open Source
    • Python Socket Programming
    • Python HTTP Server
    • Useful Tips on Python Programming
    • Python You Should Be Using It
    • Python Web Development
    • Exclusive Things About Python Socket Programming (Basics)
    • Python Programming Beginners Tutorails
    • Practical Python Programming for Non-Engineers
    • Python Programming for the Absolute Beginner
    • Data Engineer with Python
    • Versions of? Python
  • Programming in Python
    • Comments in Python
    • sprintf Python
    • Finally in Python
    • Python Multiline Comment
    • Python Data Types
    • Python Variables
    • Python Variable Types
    • Python Global Variable
    • Python Variable Scope
    • Python Private Variables
    • Python Default Arguments
    • Python Defaultdict
    • Python Command-line Arguments
    • Python try except
    • Coroutines python
    • Indentation in Python
    • Object in Python
    • Weka Python
    • Counting Sort Python
    • Hash table in Python
    • Radix Sort in Python
    • Hierarchical Cluster Python
    • Dataset in Python
    • Flask in Python
    • Python Keywords
    • Python Literals
    • Pointers in Python
    • Iterators in Python
    • Python Declare Variable
    • Python Modules
    • Python Private Method
    • Python dateutil
    • Python float to int
    • Python not equal
    • Python libraries list
    • Random forest in python
    • Data Manipulation with Python
    • Text to Speech in Python
    • Python Throw Exception
    • Python strftime
    • Python Widgets
    • Mean Shift Clustering Python
    • Sublime Text Shortcuts
    • Python User Input
    • Python Enumerate
    • Python Commands
    • Type Casting in Python
    • Python UUID
    • Abstraction in Python
    • Python Identifiers
    • Python Constants
    • What is NumPy in Python?
    • Cheat Sheet Python
  • Frameworks
    • Python Frameworks
    • Python Compilers
    • Python Editors
    • Best Compiler for Python
    • Python IDE for Windows
    • Python IDE on Linux
    • Python pseudocode
    • Iterator in Python
  • Installation
    • How To Install Python
    • Install Python on Linux
    • Install Python on Windows
    • Install Anaconda Python
  • Operator
    • Python Operators
    • Operator Precedence in Python
    • Arithmetic Operators in Python
    • Python Comparison Operators
    • Logical Operators in Python
    • Assignment Operators in Python
    • Unary Operators in Python
    • Python Ternary Operator
    • String Operators in Python
    • Python Int to String
    • Python String to Float
    • Python? string manipulation
    • Boolean Operators in Python
    • Identity Operators in Python
    • Python Bitwise Operator
    • Python Remainder Operator
    • Python object type
    • Python object serialization
    • Flask unit testing
    • Unit Testing in Python
    • Knapsack Problem Python
    • exec Python
    • Python Modulus Operator
  • Control Statement
    • Conditional Statements in Python
    • Control Statements in Python
    • If Condition in Python
    • If Else in Python
    • If Statement in Python
    • If Else Statement in Python
    • else if Statement in Python
    • Nested IF Statement in Python
    • Break Statement in Python
    • Python Switch Statement
    • Python Break Statement
  • Loops
    • Loops in Python
    • For Loop in Python
    • While Loop in Python
    • Do While Loop in Python
    • Python Nested Loops
    • Python Infinite Loop
    • Python?Event Loop
  • File Handling Python Tutorial
    • Python File Methods
    • Python Copy File
    • Python Check if File Exists
    • Python Import CSV
    • File Handling in Python
    • Python Read CSV File
    • Python write CSV file
    • Python Delete File
    • Python File readline
    • Python if main
    • Python Main Method
    • List Method in Python
    • Python List Functions
    • Python List Comprehension
    • Python List Length
    • Python List count
    • Python Lists Methods
    • Python Add List
    • Python List extend
    • Python Doubly Linked List
    • Copy List in Python
    • Python list remove()
    • Python List Index
  • Function
    • Python Built-in Functions
    • Recursive Function in Python
    • Python Range Function
    • Python Substring
    • Math Functions in Python
    • Python @property decorator
    • Python String Functions
    • Python User Defined Functions
    • Trigonometric Functions in Python
    • Python Input Function
    • Python Set Function
    • Python len Function
    • Python eval()
    • Python rstrip()
    • Pandas DataFrame.apply()
    • Python Counter
    • ord Function in Python
    • strip Function in Python
    • Split Function in Python
    • Python Round Function
    • Python Map Function
    • Python format() Function
    • Python Contextlib
    • Python Return Value
    • Filter in Python
    • Python Absolute Value
    • Python Type Function
    • Python xrange
    • Python yield
    • Max Function in Python
    • Python Power Function
    • pop() in Python
    • Python argparse
    • Python Pickle
    • Python Zip Function
    • Python Z Test
    • super() in Python
    • Python Extend
    • Python @staticmethod
    • Python Timezone
    • Timestamp to Date in Python
    • Python Timeit
    • Timsort Python
    • Python Property()
    • Python deepcopy
    • Python Dump
    • Python wait()
    • Statistical Analysis in Python
    • Python PEP8
    • Python Filter Function
    • Python if then else
    • Lambda in Python
    • Python BeautifulSoup
    • BeautifulSoup XPath
    • Beautifulsoup lxml
    • BeautifulSoup Install
    • Python Sleep
    • Python Function Generator
    • Python @classmethod decorator
    • Python Endswith
    • Python BufferedReader
    • Python Async
    • Python Parser
    • Python SystemExit
    • Python pip
    • Python kwargs
  • Array
    • Arrays in Python
    • Python string to array
    • 2D Arrays In Python
    • 3d Arrays in Python
    • Multidimensional Array in Python
    • Python Array Functions
    • String Array in Python
    • Python Sort Array
    • Python Array Length
  • OOPS Concept
    • Inheritance in? Python
    • Single Inheritance in Python
    • Overriding in Python
    • Function Overloading in Python
    • Method Overriding in Python
    • Encapsulation in Python
    • Polymorphism in Python
    • Static Method in Python
    • Method Overloading in Python
    • Operator Overloading in Python
    • Constructor in Python
    • Destructor in Python
    • Python Overloading
    • Multiple Inheritance in Python
    • Multilevel Inheritance in Python
    • Interface in Python
  • Programs
    • Patterns in Python
    • Star Patterns in Python
    • Swapping in Python
    • Factorial in Python
    • Fibonacci Series in Python
    • Reverse Number in Python
    • Binary number in Python
    • Palindrome in Python
    • Random Number Generator in Python
    • Prime Numbers in Python
    • Armstrong Number in Python
    • Perfect Number in Python
    • Strong Number in Python
    • Leap Year Program in Python
    • Anagram Program in Python
    • Square Root in Python
    • Python Reverse String
    • Python Object to String
    • Python string append
    • Python Raw String
    • Python Object to JSON
    • Python Classmethod vs Staticmethod
  • Exception
    • Python Exception Handling
    • Custom Exception in Python
    • Indentation Error in Python
    • Python Memory Error
    • Python User Defined Exception
    • Python IOError
    • Python EOFError
    • Python NotImplementedError
    • Python TypeError
    • Python ValueError
    • Python AssertionError
    • Python Unicode Error
    • Python NameError
    • Python StopIteration
    • Python OverflowError
    • Python KeyboardInterrupt
  • PySpark
    • PySpark Read CSV
    • PySpark lit()
    • PySpark Pipeline
    • PySpark Join on Multiple Columns
    • PySpark GitHub
    • PySpark to Pandas
  • NLTK
    • What is NLTK
    • NLTK Stop Words
    • NLTK Tokenize
    • NLTK Remove Punctuation
    • NLTK Sentiment Analysis
    • NLTK POS Tag
    • NLTK Lemmatizer
    • NLTK Corpus
    • NLTK Stemming
    • NLTK word_tokenize
    • NLTK WordNet
  • SpaCy
    • SpaCy ner
    • spaCy Matcher
    • spaCy Text Classification
    • spaCy Dependency Parser
    • SpaCy Tokenizer
    • SpaCy NLP
    • SpaCy models
  • Advanced
    • Python Pillow
    • Merge Dictionaries in Python
    • Dictionary Python Remove
    • Python Data Analysis Example
    • Scope in Python
    • Python Itertools
    • Python Join List
    • Python Pillow Install
    • Python Projects in GitHub
    • Python Projects with Database
    • OrderedDict in Python
    • Python Collections
    • statsmodels Python
    • Python NOT Operator
    • classmethod in Python
    • Assert in Python
    • Python References
    • Python Virtualenv
    • Python mkdir
    • Logistic Regression in Python
    • Dictionary in Python
    • Sort Dictionary in Python
    • Nested Dictionary Python
    • List of Dictionary in Python
    • Python Directories
    • Regular Expression in Python
    • Python Import Module
    • Python OS Module
    • Python Sys Module
    • Python Generators
    • Abstract Class in Python
    • Python File Operations
    • Sequences in Python
    • Stack in Python
    • Queue in Python
    • Deque in Python
    • Tuples in Python
    • Python Magic Method
    • Python Sets
    • Python Set Methods
    • Priority Queues in Python
    • Python Create Directory
    • Reverse Engineering with Python
    • Underscore in Python
    • Serverless Python
    • String Formatting in Python
    • f String in Python
    • Python isinstance
    • String Length Python
    • Python Concurrency
    • Python List
    • Python Initialize List
    • Python Unique List
    • Python Sort List
    • Selection Sort in Python
    • Python Reverse List
    • Python Empty List
    • List Comprehensions Python
    • List Operations in Python
    • Python Repository
    • Python Database Connection
    • Python SQLite
    • Data Analysis with Python
    • Python Language
    • Object Oriented Programming in Python
    • Python is Open Source Language
    • Python SQL
    • Python SQL Library
    • Python SQLite Create Database
    • Send Mail in Python
    • Bash Scripting and Python
    • Violent Python Book
    • NLP in Python
    • Matplotlib In Python
    • Gray Hat Python: Security
    • Python Subprocess
    • Python bokeh
    • Python pillow resize image
    • Python xlrd
    • Python Projects
    • Python Threading Timer
    • Python Threadpool
    • Python Statistics Module
    • How to Call a Function in Python?
    • Python Curl
    • JSON in Python
    • Python JSON to string
    • Python json.dumps
    • Python Turtle
    • Python testing framework
    • Python Unit Test
    • pass Keyword in Python
    • Tokenization in Python
    • Random Module in Python
    • Python Multiprocessing
    • Python getattr
    • Collection Module in Python
    • Python Countdown Timer
    • Python Context Manager
    • Python Event Handler
    • Python Print Table
    • Python Docstring
    • Python Dictionary Keys
    • Python Iterator Dictionary
    • Python Class Attributes
    • Python Dictionary Methods
    • Namedtuple Python
    • OpenCV Python
    • OpenCV erode
    • OpenCV save image
    • Traceback in Python
    • Decorator in Python
    • Python Pygame
    • Python Class Constants
    • Python Validation
    • Python Switch Case
    • Linked List in Python
    • DFS Algorithm in Python
    • Priority queue algorithm
    • Tree Traversal Python
    • AVL Tree Python
    • Binary Search Tree Python
    • Binary tree in Python
    • Binary search in Python
    • BFS Algorithm Python
    • Python Rest Server
    • Python Yield vs Return
    • Python Pickle vs JSON
    • Python Read Excel File
  • BeautifulSoup
    • BeautifulSoup Find
    • BeautifulSoup find by class
    • BeautifulSoup Web Scraping
    • BeautifulSoup get text
    • BeautifulSoup Table
    • BeautifulSoup Requests
  • Interview Question
    • Python Interview Questions And Answers

Related Courses

Python Certification Course

Programming Languages Courses

Angular JS Certification Training

Python Find String

By Priya PedamkarPriya Pedamkar

Python-Find-String

Introduction to Python Find String

The string is a sequence of characters. The character can be any letter, digit, whitespace character, or any special symbols. Strings in Python are immutable, which means once created, they cannot be modified. However, we can make a copy of the string and can perform various operations on it. For this, Python provides a separate class “str” for string handling and manipulations. One such operation is to find the index of a substring from the given string. Python provides three built-in methods to perform find operation. find() method is similar to the index() method, which also returns the index of a matched substring, but the difference is that find(), and rfind() returns -1 if the item to be searched is not found whereas index() throws an error.

Syntax of Python Find String

Syntax of python find string are as follows:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

1. find()

find() method returns the index of the first occurrence of the substring to be searched.

Syntax:

string_object.find(substring, start, end)

Parameters:

  • substring: It’s the text or substring that needs to be searched in string “string_object”. This is a mandatory parameter.
  • start: An optional parameter that specifies the position where searching has to start. The default value is 0. It means searching will start from the beginning of the string.
  • end: An optional parameter that specifies the position where searching has to stop. Default value is (length-1).

2. rfind()

This is similar to find() method. The difference is, the search is performed from right to the left of the string.

Syntax:

string_object.rfind(substring, start, end)

Parameters:

  • substring: Text to search.
  • start: start specifies the index from where searching has to start. The default value is 0 and length-1 for the start parameter.
  • end: end specifies the index from where searching stops, respectively. The default value is 0 and length-1 for the stop parameter.

3. index()

index() also returns the index of the searched item’s first occurrence but throws an error if the item to search is not found in the string.

Syntax:

string_object.index(substring, start, end)

Parameters:

  • substring: Text to search.
  • start: start specifies the index from where searching has to start. The default value is 0 and length-1 for the start parameter.
  • end: end specifies the index from where searching stops, respectively. The default value is 0 and length-1 for the stop parameter.

Examples of Python Find String

Below we will see the examples of Python find string:

Example #1

Python code to show the functionality of the find() method.

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,268 ratings)

Code:

"""
find() is used to find the index of substring/text in the given string
"""
print('Illustration of find() with no start and end parameters')
string = "what comes easy won't last \nwhat lasts won't come easy"
print("Input String :")
print(string)
print("index of newline :", string.find('\n'))
print("index of (won't) :", string.find("won't"))
print("index of (come) :", string.find('come'))
print("index of (easier) :", string.find('easier'))
print('\n')
print('Illustration of find() with start and end parameters')
print("index of (won't) :", string.find("won't", 18)) # start : 18
print("index of (come) :", string.find('come', 5, 15)) # start : 5 and stop = 15
print("index of (come) :", string.find('come', 10)) # start : 10

Output:

Python Find String eg1

Explanation:

find() with no start and stop parameters:

  • Index of newline ‘\n’ is printed.
  • Index of the first occurrence Python Finds String will not be printed as multiples will not be printed in the specified string. Similarly, the index of come is printed.
  • As ‘easier’ is not present in the string, so -1 will be returned.

find() with a start and stop parameters:

  • The second occurrence won’t is printed as start index = 18.
  • The first occurrence of come is printed as start index = 5 and stop index = 15.
  • The second occurrence of come is printed as start index = 10.

Example #2

Python code to illustrate the functionality of rfind() method.

Code:

"""
rfind() is used to find the index of substring/text from right to left in the given string
"""
print('Illustration of rfind() with no start and end parameters')
string = "XYZX\n987\nYZX\n05LMN"
print("input string :")
print(string)
print('\n')
print("index of newline :", string.rfind('\n'))
print("index of (ZX) :", string.rfind("ZX"))
print("index of (X) :", string.rfind('X'))
print("index of (ABC) :", string.rfind('ABC'))
print('\n')
print('Illustration of rfind() with start and end parameters')
print("index of (ZX) :", string.find('ZX', 0, 9)) # start : 0 and stop : 9
print("index of (X) :", string.find('X', 0, 10)) # start : 0 and stop : 10
print("index of newline :", string.find('\n', 6, 10)) # start : 6 and stop : 10

Output:

Python Find String eg2

Explanation:

  • rfind() with no start and end parameters.
  • index or position of the first occurrence of ‘\n’ from the right side of the string is printed.
  • similarly, indexes of the first occurrences of ZX and X from the right side are printed.
  • As substring, ABC is not present, so -1 will be returned.
  • rfind() with a start and stop parameters.
  • second occurrences of ZX and X from the right side are printed as start and stop indexes are provided in rfind() method call.
  • Similarly, the second occurrence of newline ‘\n’ is printed as a start: 6 and stop: 10, as shown in the output.

Example #3

Python code to show the functionality of the index() method.

Code:

"""
index() is used to find the index of substring/text in the given string
"""
print('<--------illustration of index()-------->')
string = "Python is an interpreted language"
print("input string :")
print(string)
print('\n')
print("index of (an) :", string.index('an'))
print("index of (space) :", string.index(" "))
print("index of (space) :", string.index(' ', 20)) # start : 20
print('\n')
print('Alert ! this will throw an error!!')
try:
    print("index of (compiled) :", string.index('compiled'))
except:
    print("index() will throw an error in case a substring is not found")

Output:

Example 3

Explanation:

  • Index() works in the same way as to find(), but the major difference is their way of handling for non matched substring.
  • If a substring is not present in the given string, then find() will return -1, whereas index() will throw an error.
  • In the above example, the error is handled using a try-except block.

Conclusion

Python provides various built-in methods to find a particular text’s index or substring in a given string. find(), rfind() and index() by default returns the index of the first occurrence of the text. However, using loops and some programming logic, we can find all the matched substrings’ possible occurrences or indexes.

Recommended Articles

This is a guide to Python Find String. Here we discuss the syntax and parameters of Python Find String along with Examples and its code implementation. You may also have a look at the following articles to learn more –

  1. String Operators in Python
  2. Arithmetic Operators in Python
  3. Substrings in Python
  4. Python Tkinter Canvas
Popular Course in this category
Python Certifications Training Program (40 Courses, 13+ Projects)
  40 Online Courses |  13 Hands-on Projects |  215+ Hours |  Verifiable Certificate of Completion
4.8
Price

View Course
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more