Use the in operator:

if "blah" not in somestring: 
    continue

Note: This is case-sensitive.

Answer from Michael Mrozek on Stack Overflow
🌐
Codecademy
codecademy.com › article › how-to-check-if-a-string-contains-a-substring-in-python
How to Check if a String Contains a Substring in Python | Codecademy
If we’re looking for a quick and readable way to check for the presence of a substring in a string, the in operator is our best bet. For more detailed checks, like finding the position of the substring or avoiding exceptions, methods like ...
Discussions

What is the most efficient way to find substrings in strings?
Easiest solution is to just use the 'in' operator like this: if "Leonardo DiCaprio" in article_title: return True And according to the top answer here it's also the fastest: whats-a-faster-operation-re-match-search-or-str-find Edit:cant get that return statement to indent for the life of me, you get the idea More on reddit.com
🌐 r/learnpython
22
4
January 11, 2022
How do I check if string contains all substrings in list?

You could try

if all([val in string for val in list]):

Which checks the truth of each check and returns True only if all are True. Otherwise you're looking at a loop (or if your lists get really big a generator).

More on reddit.com
🌐 r/learnpython
11
1
November 16, 2018
Need to find a substring with wildcards in string

Loop through each sequential set of 5 characters and compute the hamming distance with your key string.

from itertools import tee, islice

def nwise(iterable, n=2):
"""s -> (s0, s1, ..., sn-1), (s1, s2, ..., sn), (s2, s3, ..., sn+1), ...
Comes from https://stackoverflow.com/a/21303303/5087436"""
iters = tee(iterable, n)
for i, it in enumerate(iters):
next(islice(it, i, i), None)
return zip(*iters)

def hamming_distance(s1, s2):
"""Returns the number of differences between s1 and s2 (assuming equal length)"""
return sum(c1 != c2 for c1, c2 in zip(s1, s2))

dna = "ABBACAGTABTAGAAGTBABGTABGTGABAATGBAAGTGBAATTGABAGGTAAGTBAGABAAABGTTAGAAG"
key = "AGTBA"
wildcards = 3

# for each substring with length the same as your key...
for i, seq in enumerate(nwise(dna, len(key))):
d = hamming_distance(seq, key)
if d <= wildcards:
print(f'DNA at index {i}', ''.join(seq), f'matches {key} with distance {d}.')

And this will output something like:

DNA at index 5 AGTAB matches AGTBA with distance 2.
DNA at index 8 ABTAG matches AGTBA with distance 3.
DNA at index 11 AGAAG matches AGTBA with distance 3.
DNA at index 14 AGTBA matches AGTBA with distance 0.
DNA at index 18 ABGTA matches AGTBA with distance 3.
DNA at index 19 BGTAB matches AGTBA with distance 3.
DNA at index 23 BGTGA matches AGTBA with distance 2.
DNA at index 25 TGABA matches AGTBA with distance 2.
DNA at index 29 AATGB matches AGTBA with distance 3.
DNA at index 30 ATGBA matches AGTBA with distance 2.
DNA at index 31 TGBAA matches AGTBA with distance 3.
DNA at index 35 AGTGB matches AGTBA with distance 2.
DNA at index 36 GTGBA matches AGTBA with distance 3.
DNA at index 37 TGBAA matches AGTBA with distance 3.
DNA at index 40 AATTG matches AGTBA with distance 3.
DNA at index 41 ATTGA matches AGTBA with distance 2.
DNA at index 43 TGABA matches AGTBA with distance 2.
DNA at index 47 AGGTA matches AGTBA with distance 2.
DNA at index 48 GGTAA matches AGTBA with distance 2.
DNA at index 52 AGTBA matches AGTBA with distance 0.
DNA at index 56 AGABA matches AGTBA with distance 1.
DNA at index 58 ABAAA matches AGTBA with distance 3.
DNA at index 60 AAABG matches AGTBA with distance 3.
DNA at index 63 BGTTA matches AGTBA with distance 2.
DNA at index 67 AGAAG matches AGTBA with distance 3.

You could also like, sort by the hamming distance and stuff if you wanted too by using it as a key function. This should all be super efficient since it's using iterators and only loops through your key string once per iteration; so it's an O(m*n) operation where m and n are the lengths of your key string and DNA string.

Here's slightly more betterer code IMO (not sure what info is most important, so this has all the major parts); basically, we just add a namedtuple for each match to get better string representation and all the info we could want about any match:

from itertools import tee, islice
from collections import namedtuple


Match = namedtuple('Match', 'start, stop, distance, substring, key, wildcards')


def nwise(iterable, n=2):
iters = tee(iterable, n)
for i, it in enumerate(iters):
next(islice(it, i, i), None)
return zip(*iters)

def hamming_distance(s1, s2):
s = sum(c1 != c2 for c1, c2 in zip(s1, s2))
d = ''.join('*' if c1 != c2 else c1 for c1, c2 in zip(s1, s2))
return s, d

def findmatches(string, key, nwildcards):
n = len(key)
for i, seq in enumerate(nwise(string, n)):
dist, diffs = hamming_distance(seq, key)
if dist <= nwildcards:
yield Match(i, i+n, dist, ''.join(seq), key, diffs)


dna = "ABBACAGTABTAGAAGTBABGTABGTGABAATGBAAGTGBAATTGABAGGTAAGTBAGABAAABGTTAGAAG"
key = "AGTBA"
nwildcards = 3

for m in findmatches(dna, key, nwildcards):
print(m)

And this would produce output like:

Match(start=5, stop=10, distance=2, substring='AGTAB', key='AGTBA', wildcards='AGT**')
Match(start=8, stop=13, distance=3, substring='ABTAG', key='AGTBA', wildcards='A*T**')
Match(start=11, stop=16, distance=3, substring='AGAAG', key='AGTBA', wildcards='AG***')
Match(start=14, stop=19, distance=0, substring='AGTBA', key='AGTBA', wildcards='AGTBA')
Match(start=18, stop=23, distance=3, substring='ABGTA', key='AGTBA', wildcards='A***A')
Match(start=19, stop=24, distance=3, substring='BGTAB', key='AGTBA', wildcards='*GT**')
Match(start=23, stop=28, distance=2, substring='BGTGA', key='AGTBA', wildcards='*GT*A')
Match(start=25, stop=30, distance=2, substring='TGABA', key='AGTBA', wildcards='*G*BA')
Match(start=29, stop=34, distance=3, substring='AATGB', key='AGTBA', wildcards='A*T**')
Match(start=30, stop=35, distance=2, substring='ATGBA', key='AGTBA', wildcards='A**BA')
Match(start=31, stop=36, distance=3, substring='TGBAA', key='AGTBA', wildcards='*G**A')
Match(start=35, stop=40, distance=2, substring='AGTGB', key='AGTBA', wildcards='AGT**')
Match(start=36, stop=41, distance=3, substring='GTGBA', key='AGTBA', wildcards='***BA')
Match(start=37, stop=42, distance=3, substring='TGBAA', key='AGTBA', wildcards='*G**A')
Match(start=40, stop=45, distance=3, substring='AATTG', key='AGTBA', wildcards='A*T**')
Match(start=41, stop=46, distance=2, substring='ATTGA', key='AGTBA', wildcards='A*T*A')
Match(start=43, stop=48, distance=2, substring='TGABA', key='AGTBA', wildcards='*G*BA')
Match(start=47, stop=52, distance=2, substring='AGGTA', key='AGTBA', wildcards='AG**A')
Match(start=48, stop=53, distance=2, substring='GGTAA', key='AGTBA', wildcards='*GT*A')
Match(start=52, stop=57, distance=0, substring='AGTBA', key='AGTBA', wildcards='AGTBA')
Match(start=56, stop=61, distance=1, substring='AGABA', key='AGTBA', wildcards='AG*BA')
Match(start=58, stop=63, distance=3, substring='ABAAA', key='AGTBA', wildcards='A***A')
Match(start=60, stop=65, distance=3, substring='AAABG', key='AGTBA', wildcards='A**B*')
Match(start=63, stop=68, distance=2, substring='BGTTA', key='AGTBA', wildcards='*GT*A')
Match(start=67, stop=72, distance=3, substring='AGAAG', key='AGTBA', wildcards='AG***')
More on reddit.com
🌐 r/learnpython
10
12
October 10, 2018
Regex that matches a pattern anywhere in a string
1 minutes after posting and i figured it out. Hate it when this happens (i guess i just needed to write everything down to get it)! It turns out the problem isn't with my pattern, but with the method i was using. match only checks the beginning of the string search is what i needed in my case - it searches the whole string More info here More on reddit.com
🌐 r/learnpython
17
64
June 29, 2018
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-string-find
Python String find() Method - GeeksforGeeks
April 26, 2025 - find() method in Python returns the index of the first occurrence of a substring within a given string. If the substring is not found, it returns -1. This method is case-sensitive, which means "abc" is treated differently from "ABC".
🌐
Reddit
reddit.com › r/learnpython › what is the most efficient way to find substrings in strings?
r/learnpython on Reddit: What is the most efficient way to find substrings in strings?
January 11, 2022 -

Hello,

There are several ways to find substrings in string, You could use substring in string you could use string.index(substring), or you could use string.find(substring) or even use regex.

I'm trying to understand if there is a significant difference between them for my use case, which is finding people names in article titles for example:

I want to check if Leonardo DiCaprio is in Leonardo DiCaprio gets called out for boarding superyacht: ‘eco-hypocrite’

What I usually do is:

def is_substring_in_string(substring: str, string: str):        
    #same thing as before but on the article title.
    string_alphanumeric = ''.join(e for e in string if e.isalnum()).lower()

    return substring in string_alphanumeric

def main():
    names = ["Harrison Ford","Leonardo DiCaprio","Eddie Murphy","Bruce Willis","Will Smith"]

    #removes unwanted charecters such as !@#$%^&*() etc and converts to lower case
    names_alnum_lower = [''.join(e for e in x if e.isalnum()).lower() for x in names]

    article_title = "Leonardo DiCaprio gets called out for boarding superyacht: eco-hypocrite"

    for idx, lower_name in enumerate(names_alnum_lower):
        if is_substring_in_string(lower_name,article_title):
            print(f"Actor Name: '{names[idx]}' is in article title '{article_title}'")

if __name__ == '__main__':
    main()

Imagine there are a bunch of articles and people's names. Is this method acceptable or will I be better off using regex or something else?

🌐
YouTube
youtube.com › watch
Identifying a Substring Within a Python String - YouTube
If you’re new to programming or come from a programming language other than Python, you may be looking for the best way to check whether a string contains an...
Published   April 6, 2023
🌐
Mimo
mimo.org › glossary › python › string-find
Python string.find(): Syntax, Usage, and Examples
The method specifically returns the index of the first occurrence of the substring, making it different from other search methods in languages like Java or JavaScript. The .find() method is a built-in string method used to locate the starting index of the first occurrence of a substring within ...
Find elsewhere
🌐
W3Schools
w3schools.com › python › ref_string_find.asp
Python String find() Method
Remove List Duplicates Reverse ... Python Interview Q&A Python Bootcamp Python Training ... The find() method finds the first occurrence of the specified value....
🌐
CodeSignal
codesignal.com › learn › courses › practicing-string-operations-and-type-conversions-in-python › lessons › exploring-substring-search-in-python-strings
Exploring Substring Search in Python Strings
In original.find(substring), we pass the 'substring' that we want to locate. The function begins the search from the beginning as we have not specified a starting position. ... The following step is to locate the rest of the instances of the 'substring' in the 'original'.
🌐
Sentry
sentry.io › sentry answers › python › extract a substring from a string in python
Extract a substring from a string in Python
2 weeks ago - Extract substrings from Python strings using slice notation with [start:end] indexes, or use re.search() with regex patterns for matching specific formats
🌐
Programiz
programiz.com › python-programming › methods › string › find
Python String find()
print(quote.find('small things', 10)) # Substring is searched in ' small things with great love' print(quote.find('small things', 2)) # Substring is searched in 'hings with great lov'
🌐
freeCodeCamp
freecodecamp.org › news › python-find-how-to-search-for-a-substring-in-a-string
Python find() – How to Search for a Substring in a String
July 25, 2022 - The return value of the find() method is an integer value. If the substring is present in the string, find() returns the index, or the character position, of the first occurrence of the specified substring from that given string.
🌐
Great Learning
mygreatlearning.com › blog › it/software development › what is a python substring?
What is a Python Substring and How to Create One
June 11, 2025 - In this course, you will learn the fundamentals of Python: from basic syntax to mastering data structures, loops, and functions. You will also explore OOP concepts and objects to build robust programs. ... Let's look at examples. This is the most common way to get a substring. You specify a starting index and an ending index. my_string = "hello world" # Get characters from index 0 up to (but not including) index 5 sub1 = my_string[0:5] print(f"Substring 1: '{sub1}'") # Get characters from index 6 up to (but not including) index 11 sub2 = my_string[6:11] print(f"Substring 2: '{sub2}'") # Get a single character (from index 4 to 5) sub3 = my_string[4:5] print(f"Substring 3: '{sub3}'")
🌐
FavTutor
favtutor.com › blogs › string-contains-substring-python
Check if Python string contains substring: 3 Methods (with code)
January 23, 2023 - You can use the .findall() function instead of .search() function to find every matching substring that ends with punctuation. Python has __contains__() as an instance method to check for substrings in a string.
🌐
Real Python
realpython.com › lessons › python-string-contains-substring-summary
Check if a Python String Contains a Substring (Summary) (Video) – Real Python
In the process, you learned that the best way to check whether a string contains a substring in Python is to use the in membership operator. You also learned how to descriptively use two other string methods, which are often misused to check ...
Published   April 4, 2023
🌐
Plain English
python.plainenglish.io › how-to-check-if-a-python-string-contains-a-substring-5de51d3eaabe
How to Check Substrings in Python Strings | Python in Plain English
December 5, 2024 - Learn how to check if a Python string contains a substring using methods like in, find(), and regular expressions, with case-insensitive…
🌐
Codecademy
codecademy.com › docs › python › substrings
Python | Substrings | Codecademy
June 18, 2025 - The string method .find() can also be used to find a subset. It returns the index of the first occurrence of the substring. If the substring is not found, it returns -1. ... Use slicing for efficiency: String slicing is optimized in Python and ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › find-the-index-of-a-substring-in-python
Find the Index of a Substring in Python - GeeksforGeeks
July 23, 2025 - In this article, we will explore ... in Python. The find() method searches for the first occurrence of the specified substring and returns its starting index. If the substring is not found, it returns -1. ... s = "GeeksforGeeks" # Define the ...
🌐
Real Python
realpython.com › python-string-contains-substring
How to Check if a Python String Contains a Substring – Real Python
December 1, 2024 - The in membership operator is the recommended way to check if a Python string contains a substring. Converting input text to lowercase generalizes substring checks by removing case sensitivity.
🌐
Tutorialspoint
tutorialspoint.com › python › string_find.htm
Python String find() Method
Welcome to Tutorialspoint." str2 = " "; result= str1.find(str2, 12, 15) print("The index where the substring is found:", result) The following output is obtained by executing the above program - ... If the same substring is appeared for more than one time in the created string, then based on the starting or ending index that is specified as the function's parameters, the resultant index is obtained.