Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string contains at least five characters in python

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.

like image 861
O JOE Avatar asked Mar 05 '23 02:03

O JOE


2 Answers

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
like image 100
yatu Avatar answered Mar 09 '23 10:03

yatu


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).

like image 33
Cohan Avatar answered Mar 09 '23 10:03

Cohan