-3

String fails to match by and or, in search. Why?

string = 'This is some text with an email add: myusername@domain.com'
a = re.findall('[\w]+@[\w]+\.[\w]{3}',string)
b = string.split(' ')
print (a)
print (b)

if a==b:
    # also tried: if a in b:
    print(a, ' yes it is found')
else:
    print('not !?!?!')
['myusername@domain.com']
['This', 'is', 'some', 'text', 'with', 'an', 'email', 'add:', 'myusername@domain.com']
not !?!?!
Majoris
  • 2,963
  • 6
  • 47
  • 81

2 Answers2

2

a and b are both lists. They are not equal. And a is not an element of b. b contains only strings, not lists.

If you want to check if the single string contained in a is also contained in b, you can do this:

if a[0] in b:
    print("Yes, a[0] is in b")

In general, if you want to check if any element of one list is contained in another list, there are various ways to do it, but here is one:

if any(element in b for element in a):
    print("Some element of a is in b")
khelwood
  • 55,782
  • 14
  • 81
  • 108
0

Well a doesn't equal to b so it will never make it inside the if statement, you should loop over one list and compare it's elements to the other list as follow

import re

string = 'This is some text with an email add: myusername@domain.com'
a = re.findall('[\w]+@[\w]+\.[\w]{3}',string)
b = string.split(' ')
print (a)
print (b)

for aa in a:
    if aa in b: # tried
        print(a, ' yes it is found')
else:
    print('not !?!?!')
Marsilinou Zaky
  • 1,038
  • 7
  • 17