2016-08-03 73 views
0

給定一個字符串s = "Leonhard Euler",我需要找到我的surname數組中的元素是否是s的子串。例如:如何查找數組中的元素是否是字符串的子串?

s = "Leonhard Euler" 
surnames = ["Cantor", "Euler", "Fermat", "Gauss", "Newton", "Pascal"] 
if any(surnames) in s: 
    print("We've got a famous mathematician!") 
+0

什麼問題? – wwii

+1

可能的重複[是否Python有一個字符串包含substring方法?](http://stackoverflow.com/questions/3437059/does-python-have-a-string-contains-substring-method) – Matthew

+0

這不是什麼'任何'工作。嘗試'如果有的話(姓中s姓氏):' –

回答

1

如果你不需要知道哪個姓是在是你能做到這一點使用任何與列表理解:

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

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

這將適用於s = "Leonhard Euler"s = "Euler Leonhard"

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

循環遍歷姓氏和檢查每個字符串,如果以S

0

的一個子其實我沒有測試的代碼,但應該是這樣的(如果我理解這個問題):

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

如果存在多個匹配項,此實現將多次打印。我認爲OP只希望它打印一次,這意味着當你找到一場比賽時,你需要「跳出」循環。 – Harrison

2

將字符串拆分爲列表後,可以使用集合的isdisjoint屬性,以檢查集合中的兩個列表是否具有任何共同的元素。

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!") 
相關問題