Python How To Find Substring In String
Python provides the tools to easily find a substring inside a string. You can do this with the find() function or you could use a regex. We are going to talk about regexes a little further on in this guide but using a regex is actually my preferred way of doing things.
You can use the find() function to find a substring inside a string. This will return the index at which the substring is found.
Here is an example:
string1 = "This is my big string with words like octopus, zebra, and sardine." x = string1.find('octopus') print( x)
This would output: 38
To test whether or not a value was found you could use this:
if string1.find('octopus') > -1: print("found") else: print("nothing...")
You can also specify a starting index to start searching at like this:
x = string1.find('is', 5) print( x)
You could specify an ending index like this if you only want to search in this range.
x = string1.find('is', 5, 25) print( x)
Python - Find a Substring using Regex
You can also find a substring using a regex.
string1 = "This is my big string with words like octopus, zebra, and sardine." m = re.search("(octopus)", string1) if m: print( m.groups(1) )
This should print the following:
You can also use a regex to find multiple substrings inside a string.
string2 = "There is a rock on the rocky mountain but there has been no rockslide." m = re.findall('(rock\w*)', string2) print(m)
This would give us the output:
['rock', 'rocky', 'rockslide']