Before updated question:
As per my comment, I think you are using the wrong approach. To me it seems you can simply use in
:
words = ['cat', 'caterpillar', 'monkey', 'monk', 'doggy', 'doggo', 'dog']
if 'cat' in words:
print("yes")
else:
print("no")
Returns: yes
words = ['cats', 'caterpillar', 'monkey', 'monk', 'doggy', 'doggo', 'dog']
if 'cat' in words:
print("yes")
else:
print("no")
Returns: no
After updated question:
Now if your sample data does not actually reflect your needs but you are interested to find a substring within a list element, you could try:
import re
words = ['MX_QW-765', 'RUC_PO-345', 'RUC_POLO-209']
srch = 'PO'
r = re.compile(fr'(?<=_){srch}(?=-)')
print(list(filter(r.findall, words)))
Or using match
:
import re
words = ['MX_QW-765', 'RUC_PO-345', 'RUC_POLO-209']
srch = 'PO'
r = re.compile(fr'^.*(?<=_){srch}(?=-).*$')
print(list(filter(r.match, words)))
This will return a list of items (in this case just ['RUC_PO-345']
) that follow the pattern. I used the above regular pattern to make sure your searchvalue won't be at the start of the searchstrings, but would be after an underscore, and followed by a -
.
Now if you have a list of products you want to find, consider the below:
import re
words = ['MX_QW-765', 'RUC_PO-345', 'RUC_POLO-209']
srch = ['PO', 'QW']
r = re.compile(fr'(?<=_)({"|".join(srch)})(?=-)')
print(list(filter(r.findall, words)))
Or again using match
:
import re
words = ['MX_QW-765', 'RUC_PO-345', 'RUC_POLO-209']
srch = ['PO', 'QW']
r = re.compile(fr'^.*(?<=_)({"|".join(srch)})(?=-).*$')
print(list(filter(r.match, words)))
Both would return: ['MX_QW-765', 'RUC_PO-345']
Note that if you don't have f-strings supported you can also concat your variable into the pattern.