如何查找数组中的元素是否是字符串的子字符串?

时间:2016-08-03 14:59:38

标签: python

给定一个字符串s = "Leonhard Euler",我需要找到我的姓氏数组中的元素是否是s的子字符串。例如:

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

5 个答案:

答案 0 :(得分:5)

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

这适用于s = "Leonhard Euler"s = "Euler Leonhard"

答案 1 :(得分: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!")

答案 2 :(得分: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

的子字符串

答案 3 :(得分:1)

如果你不需要知道s中的姓氏,你可以使用任何和列表理解来做到这一点:

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

答案 4 :(得分:0)

实际上我没有测试代码,但应该是这样的(如果我理解了这个问题):

var con = ConfigurationManager.ConnectionStrings["Oracle"].ConnectionString;