Reputation: 3390
I have an array of Strings. I'd like to evict all elements which start with a pattern. The pattern is contained in another array.
words=[] # contains the word lists
banned_words = ["http:","https:","mailto:"]
for word in words:
if (word.startswith(banned_words)):
continue
addWord(word)
I'm not including the addWord function for simplicity, however my attempt was to use the startsWith against the array of banned words. But it does not work. I could loop on each banned_words element and it will eventually work. However, is there a simpler approach to remove elements from an array whose string starts with (array) ? Thanks
Upvotes: 0
Views: 798
Reputation: 693
As Tomerikoo has said
>>> help(str.startswith)
startswith(...)
S.startswith(prefix[, start[, end]]) -> bool
Return True if S starts with the specified prefix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
prefix can also be a tuple of strings to try.
"prefix can also be a tuple of strings to try.". So it can also just be:
for word in words:
if word.startswith(tuple(banned_words))
Upvotes: 1
Reputation: 614
You can use list comprehension with a filter (more info here)
final = [word for word in words if not any(word.startswith(t) for t in banned_words)]
Upvotes: 1