Use find() method to find substring in string python. If the string is found then this method returns the index of the first occurrence of the substring and If not found, it returns -1.
Start and End are optional parameters by default it takes 0 and length-1 as starting and ending indexes where ending indexes are not included in our search.
Example Find substring in string python
Simple python example code- How to use find() in if statement.
word = 'Python programing tutorials and examples' # returns first occurrence of Substring result = word.find('Python') print("Substring 'Python' index:", result) # How to use find() in if statement if word.find('and') != -1: print("Substring Found") else: print("Substring Not Found")
find() With start and end Arguments
word = 'Python programing tutorials and examples' # Substring is searched in full string print(word.find('Python', 0)) # Substring is searched in ' programing tutorials and examples' print(word.find('small things', 6)) # Substring is searched in 'programing tutorials and example' print(word.find('and', 10, -1))
Do comment if you have any doubts and suggestions on this Python substring topic.
Note: IDE: PyCharm 2021.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.