Created
July 26, 2016 20:22
-
-
Save lsloan/ec4420b07e0180e7fbd7350b9d048f9b to your computer and use it in GitHub Desktop.
Python: A couple of methods to check whether a string contains any or all of the characters from a second string.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def stringContainsAnyCharacters(string, characters): | |
""" | |
Check whether 'string' contains any characters from string 'characters'. | |
:param string: String to check for wanted characters | |
:type string: str | |
:param characters: String of characters to be found | |
:type characters: str | |
:return: True if any characters are found, False otherwise | |
:rtype: bool | |
""" | |
assert type(string) is str | |
assert type(characters) is str | |
return True in [character in string for character in characters] | |
def stringContainsAllCharacters(string, characters): | |
""" | |
Check whether 'string' contains all characters from string 'characters'. | |
:param string: String to check for wanted characters | |
:type string: str | |
:param characters: String of characters to be found | |
:type characters: str | |
:return: True if all characters are found, False otherwise | |
:rtype: bool | |
""" | |
assert type(string) is str | |
assert type(characters) is str | |
return False not in [character in string for character in characters] | |
if __name__ == '__main__': | |
assert stringContainsAnyCharacters('*.py', '*?[]') | |
assert not stringContainsAnyCharacters('file.txt', '*?[]') | |
assert stringContainsAllCharacters('43221', '123') | |
assert not stringContainsAllCharacters('134', '123') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment