In this source code example, we will demonstrate how to use the Python string find() method effectively to find a substring in a string.
The following illustrates the syntax of the find() method:The following example shows how to use the find() method to find the substring 'Source' in the string 'Source Code Examples':
The following example uses the find() method to locate the substring 'Source' in the string 'Source Source Code Examples' within the slice str[1:]:
The following example returns -1 because the substring 'Python' doesn’t exist in the string 'Source Code Examples':
Python string find() method
The find() is a string method that finds a substring in a string and returns the index of the substring.The following illustrates the syntax of the find() method:
str.find(sub[, start[, end]])The find() method accepts three parameters:
- sub is the substring to look for in the str.
- start and end parameters are interpreted as in the slice str[start:end], which specifies where to search for the substring sub.
Python string find() method examples
s = 'Source Code Examples'
result = s.find('Source')
print(result)
Output:
0
s = 'Source Source Code Examples'
result = s.find('Source', 1)
print(result)
Output:
7
s = 'Source Code Examples'
result = s.find('Python')
print(result)
Output:
-1
Related Python String Examples
- Python string literals
- Python string length example
- Python String join() method example
- Python string split() method example
- Python String index() method example
- Python string find() method example
- Python string startswith() method example
- Python string endswith() method example
- Python String lower() method example
- Python String upper() method example
- Python string title() method example
- Python string capitalize() method example
- Python string islower() method example
- Python string istitle() method example
- Python string isupper() method example
- Python string swapcase() method example
- Python string strip() method example
- Python string replace() method example
- Python string isdigit() method example
- Python string isdecimal() method example
- Python string isnumeric() method example
- Python string isalpha() method example
- Python string isalnum() method example
Free Spring Boot Tutorial - 5 Hours Full Course
Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course