Home > Back-end >  Python substring in string when parts of the substring is not consequential
Python substring in string when parts of the substring is not consequential

Time:12-31

Say this is my string: http://www.test.com/1/page/ And this is my sub_string: www.test.com/2/page/

Now if I run

sub_string in string

The result will obviously be False because 2 is not in the string. However, I don't care about that part. The only parts I care about are www.test.com and page. I want only these parts to be checked, and don't care about what's in between them. How can I perform a search in that way, so the results would be True?

CodePudding user response:

You can use regex.

import regex as re
test_string="www.test.com/2/page/"
len(re.findall(".*www\.test\.com\/[0-9]\/page\/",test_string))>0

Output:
True

CodePudding user response:

You can use regex:

import re
all_locs = re.findall('www\.test\.com/[0-9] /page/', source_string)

This will return all locations where the substring appears in. An empty list means it didn't appear

CodePudding user response:

you can simply use:

if substring in string.lower():
    print("Exists")
else:
    print("Does not exist")

or regex:

import re
for match in re.findall('www\.test\.com/[0-9] /page/', str):
print(match)
  • Related