Python string find() method example

In this source code example, we will demonstrate how to use the Python string find() method effectively to find a substring in a string.

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

The following example shows how to use the find() method to find the substring 'Source' in the string 'Source Code Examples':

s = 'Source Code Examples'
result = s.find('Source')

print(result)

Output:

0
The following example uses the find() method to locate the substring 'Source' in the string 'Source Source Code Examples' within the slice str[1:]:

s = 'Source Source Code Examples'
result = s.find('Source', 1)

print(result)

Output:

7
The following example returns -1 because the substring 'Python' doesn’t exist in the string 'Source Code Examples':

s = 'Source Code Examples'
result = s.find('Python')

print(result)

Output:

-1

Related Python String Examples

  1. Python string literals
  2. Python string length example
  3. Python String join() method example
  4. Python string split() method example
  5. Python String index() method example
  6. Python string find() method example
  7. Python string startswith() method example
  8. Python string endswith() method example
  9. Python String lower() method example
  10. Python String upper() method example
  11. Python string title() method example
  12. Python string capitalize() method example
  13. Python string islower() method example
  14. Python string istitle() method example
  15. Python string isupper() method example
  16. Python string swapcase() method example
  17. Python string strip() method example
  18. Python string replace() method example
  19. Python string isdigit() method example
  20. Python string isdecimal() method example
  21. Python string isnumeric() method example
  22. Python string isalpha() method example
  23. Python string isalnum() method example

Comments