0

Given a string s = "Leonhard Euler", I need to find if an element in my surname array is a substring of s. For example:

s = "Leonhard Euler"
surnames = ["Cantor", "Euler", "Fermat", "Gauss", "Newton", "Pascal"]
if any(surnames) in s:
    print("We've got a famous mathematician!")
martineau
  • 119,623
  • 25
  • 170
  • 301
Carlos Afonso
  • 1,927
  • 1
  • 12
  • 22
  • What is the question? – wwii Aug 03 '16 at 15:01
  • 1
    Possible duplicate of [Does Python have a string contains substring method?](http://stackoverflow.com/questions/3437059/does-python-have-a-string-contains-substring-method) – Matthew Aug 03 '16 at 15:02
  • That's not how `any` works. Try `if any(surname in s for surname in surnames):` – Aran-Fey Aug 03 '16 at 15:03
  • 1
    `if any(x in s for x in surnames)` ? keep in mind that this would pass `'Eu'` to also count as true. Better idea is to split your name into individual names and match exact words. – R Nar Aug 03 '16 at 15:03

5 Answers5

5

Consider if any(i in surnames for i in s.split()):.

This will work for both s = "Leonhard Euler" and s = "Euler Leonhard".

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
2

You can use isdisjoint attribute of sets after splitting the string to list to check if the two lists casted to sets have any elements in common.

s = "Leonhard Euler"
surnames = ["Cantor", "Euler", "Fermat", "Gauss", "Newton", "Pascal"]

strlist = s.split()
if not set(strlist).isdisjoint(surnames):
    print("We've got a famous mathematician!")
XZ6H
  • 1,779
  • 19
  • 25
1
s = "Leonhard Euler"
surnames = ["Cantor", "Euler", "Fermat", "Gauss", "Newton", "Pascal"]

for surname in surnames:
   if(surname in s):
       print("We've got a famous mathematician!")

Loops through each string in surnames and checks if its a substring of s

Roy
  • 3,027
  • 4
  • 29
  • 43
1

If you don't need to know which surname is in s you can do that using any and list comprehension:

if any(surname in s for surname in surnames):
    print("We've got a famous mathematician!")
Xavier C.
  • 1,921
  • 15
  • 22
0

Actually I didn't test the the code but should be something like this (if I understood the question):

for surname in surnames:
  if surname in s:
    print("We've got a famous mathematician!")
  • This implementation will print multiple times if there are multiple matches. I think that OP only wants it to print once, which means you would need to `break` out of the loop when you find a match. – Harrison Aug 03 '16 at 15:27