Carlos Afonso
Carlos Afonso

Reputation: 1957

how to find if an element from an array is a substring of a string?

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

Upvotes: 0

Views: 159

Answers (5)

Xavier C.
Xavier C.

Reputation: 1981

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

Upvotes: 1

XZ6H
XZ6H

Reputation: 1789

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

Upvotes: 2

Michele
Michele

Reputation: 1

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

Upvotes: 0

Roy
Roy

Reputation: 3267

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

Upvotes: 1

DeepSpace
DeepSpace

Reputation: 81594

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

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

Upvotes: 5

Related Questions