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!")
4
  • What is the question? Commented Aug 3, 2016 at 15:01
  • 1
    Possible duplicate of Does Python have a string contains substring method? Commented Aug 3, 2016 at 15:02
  • That's not how any works. Try if any(surname in s for surname in surnames): Commented Aug 3, 2016 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. Commented Aug 3, 2016 at 15:03

5 Answers 5

5

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

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

Sign up to request clarification or add additional context in comments.

Comments

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!")

Comments

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!")

Comments

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

Comments

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!")

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.