There are few ways of doing this problem which I am sharing here:
- We can simply use string function startwith() to do this problem
Syntax for this is:
str.startwith(prefix[,start[, end]])
Prefix will be any string or tuple of string to be checked while start and end will be optional
a = ['rtvg_c1.4.doc', 'vgft_c2.1.pdf', 'D4Q_d1.8.ppt', 'ADk_d3.0.pdf']
b = ['rtvg', 'D4Q']
result = [i for i in a if i.startswith(tuple(b))]
print(result)
output:-['rtvg_c1.4.doc', 'D4Q_d1.8.ppt']
- Second way is to use regular expression to solve this problem.
import re
a = ['rtvg_c1.4.doc', 'vgft_c2.1.pdf', 'D4Q_d1.8.ppt', 'ADk_d3.0.pdf']
b =['rtvg', 'D4Q']
pattern = re.compile("|".join(b))
result = [i for i in a if pattern.match(i)]
print(result)
output:-['rtvg_c1.4.doc', 'D4Q_d1.8.ppt']
- We have other approaches for matching as well if we want to find strings that is common in both the list. For this we will use set method which is best to do
a = ['rtvg_c1.4.doc', 'vgft_c2.1.pdf', 'D4Q_d1.8.ppt', 'ADk_d3.0.pdf']
b = ['rtvg_c1.4.doc', 'D4Q']
set(a) & set(b)
output:-{'rtvg_c1.4.doc'}
You can have a look at the following video tutorial to know clear all your doubts:-