Skip to content

Instantly share code, notes, and snippets.

@samredai
Last active December 15, 2018 15:58
Show Gist options
  • Save samredai/58e6c8936d4beb35a6ae2866adffd68a to your computer and use it in GitHub Desktop.
Save samredai/58e6c8936d4beb35a6ae2866adffd68a to your computer and use it in GitHub Desktop.
Python: Find and Remove a String from a List Using fnmatch (Including Using Wildcards)
import fnmatch
l = ["imagine", "if", "this", "was", "a", "super", "duper", "long", "list"]
thisMatches = fnmatch.filter(l, "this")
print(thisMatches)
#['this']
#Using ? as a single-character wildcard
uperMatches = fnmatch.filter(l, "?uper")
print(uperMatches)
#['super', 'duper']
#Using * as a multi-character wildcard
isMatches = fnmatch.filter(l, "*is*")
print(isMatches)
#['this', 'list']
#Then do this to remove what was found
for match in isMatches:
l.remove(match)
print(l)
#['imagine', 'if', 'was', 'a', 'super', 'duper', 'long']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment