我在使用python查找列表中的字符串的一部分時遇到了一個小問題。如何將字符串與列表中的「模式」分開
我從文件加載字符串和值是下列之一:(none, 1 from list, 2 from list, 3 from list or more...)
我需要根據字符串是否等於""
不同的動作來執行,該字符串等於1 element from list
,或者如果String是2個或更多元素。例如:
List = [ 'Aaron', 'Albert', 'Arcady', 'Leo', 'John' ... ]
String = "" #this is just example
String = "Aaron" #this is just example
String = "AaronAlbert" #this is just example
String = "LeoJohnAaron" #this is just example
我創造了這樣的事情:
if String == "": #this works well on Strings with 0 values
print "something"
elif String in List: #this works well on Strings with 1 value
print "something else"
elif ... #dont know what now
最好的辦法是在此字符串從列表中拆分模式。我試圖:
String.Find(x) #failed.
我試圖找到類似的帖子,但不能。
你在做什麼樣的動作?我的意思是:如果文本是「LeoJohnAaron」,會發生什麼? 「LeoJohn」和「LeoJohnAaron」之間會有什麼聯繫,或者代碼是否完全不同? – Bakuriu
如果文字是LeoJohnAaron應該 例如做2個動作: 從這個字符串 的另一個字符串。減去lenght和分離線 但它只是一個例子打印這些名字。 :) – degath
「LeoJohnLeoLeo」會發生什麼?重複計數?訂單是否重要?一般的做法是使用正則表達式,例如're.findall('({})'.format('|'.join(map(re.escape,names))),text)'循環遍歷匹配,但根據我指出的一些因素,更簡單的解決方案可能會更好。 – Bakuriu