Python's way of determining whether a string contains substrings

  • 2020-04-02 14:43:07
  • OfStack

This example shows how python determines whether a string contains substrings. Share with you for your reference. The details are as follows:

Python's string object does not contain a method to determine whether it contains substrings using the method string.contains, but python has an easier way to replace the contains function.

Method 1: implement the functionality of contains using the in method:


site = '//www.jb51.net/'
if "jb51" in site:
   print('site contains jb51')

Output: site contains jb51

Method 2: implement the contains functionality using the find function


s = "This be a string"
if s.find("is") == -1:
  print "No 'is' here!"
else:
  print "Found 'is' in the string."

I hope this article has helped you with your Python programming.


Related articles: