Reputation: 1957
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
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
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
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
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
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