2016-10-01 166 views
2

哪一种检查字符串元组中是否存在多个子字符串的最优雅方法?python:检查子字符串是否在字符串元组中

tuple = ('first-second', 'second-third', 'third-first') 
substr1 = 'first' 
substr2 = 'second' 
substr3 = 'third' 
#if substr1 in tuple and substr2 in tuple and substr3 in tuple: 
# should return True 
+3

不要使用'tuple'这是一个Python关键字。 – AChampion

+1

@AChampion它不是一个关键字。如果是这样,分配给它甚至不会工作。 –

+0

'tuple'是一个内建的 - 感谢您的纠正。 – AChampion

回答

2

您需要遍历元组的每个子,因此使用anyall

all(any(substr in s for s in data) for substr in ['first', 'second', 'third']) 
+0

不错,我喜欢这个!谢谢。 –

2
any(substr in str_ for str_ in tuple_) 

您可以用开始和all()看为好。

+1

就像你修复'tuple_',但后来使用'str' ... – AChampion

+0

哈哈这是一个错字。谢谢。 – s16h

+0

我仍然猜想另一个str是 –

相关问题