Python String find() Method

21-02-23 Ahmed Obaid 1357 0

​The find() function returns the index number of the first occurrence of a substring in the specified string (case sensitive). If the substring is not found, it returns -1.


How to formulate it like this:

string. find(substring, start, end)

Parameters:

substring : (required) A substring that must be searched for in the given string.

start ( optional ) : ( Optional ) The starting position where the sub-string within the string needs to be checked.

End ( ) : ( Optional ) The index of the end within the string that the search ends with. The default is the end of the string

Return value: The find() function returns an integer of the index number of the first occurrence of a substring in the specified string. If the substring is not found, it returns -1.


We will use the find() function without the optional ( start ) and ( end ) parameters. We'll just use the substring parameter to find the index number of the first occurrence of a substring in the given string.

In the following example, we will search for the index number of the first occurrence of the substring represented by the word (With ),

Example:

#undefined The string to be searched
 string = "learn python With ahmed obaid"
 # Searches the given string for the index number of the first occurrence of the substring and returns an integer
 print(string. find ("With"))

 The output will be:

 13

 In the following example, we will use the find() function with optional (start) and (end) parameters.

 Example:

 # The string to be searched
 string = "learn python With ahmed obaid"
 # Searches the given string for the index number of the first occurrence of the substring and returns an integer
 # Noting that we started the search from index #2
 # Substring not found, it returns -1.
 print(string. find ("le", 2))
 # Searches the given string for the index number of the first occurrence of the substring and returns an integer
 # Noting that we started the search process from index number 0 to the end index number 10
 print(string. find ("py", 0, 10))
 # Searches the given string for the index number of the first occurrence of the substring and returns an integer
 # Noting that we started the search process from index number 2 to the end index number 30
 print(string. find ("ahmed", 10, undefined 30))

 The output will be:

 -1
 6
 18

 External sources:

 Built-in functions - official Python documentation

 If you have any questions or concerns, leave them in the comments



Tags


Python python data types Python String string methods python String search functions in Python python string find method

Share page