string contains sub string in python

There are two common ways to check if a string contains a substring in Python:

  1. Using the in keyword:
main.py
my_string = "hello world"
if "hello" in my_string:
    print("'%s' contains the substring '%s'" % (my_string, "hello"))
120 chars
4 lines
  1. Using the find() function:
main.py
my_string = "hello world"
if my_string.find("world") != -1:
    print("'%s' contains the substring '%s'" % (my_string, "world"))
129 chars
4 lines

Both of these methods return True if the substring is found in the string and False otherwise. The find() function returns the index of the first occurrence of the substring, or -1 if the substring is not found.

gistlibby LogSnag