check substring in string code example

Example 1: python string in string

>>> str = "Messi is the best soccer player"
>>> "soccer" in str
True
>>> "football" in str
False

Example 2: check if string contains substring

Like this:

if (str.indexOf("Yes") >= 0)
...or you can use the tilde operator:

if (~str.indexOf("Yes"))
This works because indexOf() returns -1 if the string wasn't found at all.

Note that this is case-sensitive.
If you want a case-insensitive search, you can write

if (str.toLowerCase().indexOf("yes") >= 0)
Or:

if (/yes/i.test(str))

Example 3: check string line python

def search_string_in_file(file_name, string_to_search):
    """Search for the given string in file and return lines containing that string,
    along with line numbers"""
    line_number = 0
    list_of_results = []
    # Open the file in read only mode
    with open(file_name, 'r') as read_obj:
        # Read all lines in the file one by one
        for line in read_obj:
            # For each line, check if line contains the string
            line_number += 1
            if string_to_search in line:
                # If yes, then add the line number & line as a tuple in the list
                list_of_results.append((line_number, line.rstrip()))
 
    # Return list of tuples containing line numbers and lines where string is found
    return list_of_results

Tags:

Misc Example