Python | Find a Substring

We can check whether a substring is present in a string using the Python find() function. If the find() function returns 0 or a positive number, the substring is present.

The system of find() function.

string.find(substring[, start[, end]])

substring: The substring to be searched.

start: Starting index of the range where the substring will be searched. Default value is 0 if not specified.

end: Last index of the range where the substring will be searched. Default value is the length of the string if not specified.

If the substring is present, the function returns the index where the substring starts in the string. If it does not , it return -1.

 str = "experience is the name everyone gives to their mistakes."
 if (str.find("everyone") != -1):
   print ("Substring \"everyone\" is present.")
 else:
   print ("Substring \"everyone\" is not present.")
 if (str.find("none") != -1):
   print ("Substring \"none\" is present.")
 else:
   print ("Substring \"none\" is not present.")

The substring is passed to the find() function. If the return value is not -1, it prints that the substring is present, otherwise, not present.

Output:

 python test.py
 Substring "everyone" is present.
 Substring "none" is not present.


This artical is contributed by . If you also want to contribute, click here.

Leave a Reply

Your email address will not be published. Required fields are marked *

0
0
0
0
2
0