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.
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 want to use count :
var1 = "today news report"
var2 = "news report"
count = 0
for letter in set(var1):
if letter != ' ': # Check if space
count += (list(set(var2))).count(letter)
print("yes") if count >= 5 else print ("nooo")
#if count >= 5:
# print ("yes")
#else:
# print ("nooo")
#count = 8
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.