Am trying to check string
contains at least five characters
in var1
. Am using count
but it doesn't work as i expects.Meanwhile with the var2
it contains more than five characters
from the var1
.
var1 = "today news report"
var2 = "news report"
if var2.count(var1) >= 5:
print("yes")
else:
print("nooooooo")
Your suggestions are welcome to achieve that.
str.count
is searching for exact matches of var1
a in var2
. Instead you could use a sets, and see if the length of the intersection is greater than the threshold:
var1 = "today news report"
var2 = "news report"
if len(set(var1) & set(var2)) >= 5:
print("yes")
else:
print("nooooooo")
# yes
if you want to see if var2
contains 5 or more of the same characters found in var1
you can use Python's set
structure which has an set.intersection()
method. The intersection()
method will convert what is passed into anoter set and return elements that are the same between the two.
var1 = "today news report"
var2 = "news report"
if len(set(var1).intersection(var2)) >= 5:
print("Yes")
else:
print("No")
# Yes
You can see that set
gives you all the unique characters in var1
and the intersection
gives you only characters that are shared.
print(set(var1))
# {'d', ' ', 'w', 'n', 't', 's', 'r', 'y', 'o', 'a', 'e', 'p'}
print(set(var1).intersection(var2))
# {'r', 'n', 'p', 's', 'e', 'o', 'w', ' ', 't'}
The &
operator can be used to get the intersection as well, so set(var1).intersection(var2)
is equivalent to set(var1) & set(var2)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With