Test if string ONLY contains given characters

前端 未结 7 533
甜味超标
甜味超标 2021-01-12 13:19

What\'s the easiest way to check if a string only contains certain specified characters in Python? (Without using RegEx or anything, of course)

Specifically, I have

相关标签:
7条回答
  • 2021-01-12 13:49

    Something like this:

    strings = ['aba', 'acba', 'caz']
    given = "abc"
    filter(lambda string: all(char in given for char in string), strings)
    
    0 讨论(0)
  • 2021-01-12 13:52

    Assuming the discrepancy in your example is a typo, then this should work:

    my_list = ['aba', 'acba', 'caz']
    result = [s for s in my_list if not s.strip('abc')]
    

    results in ['aba', 'acba']. string.strip(characters) will return an empty string if the string to be stripped contains nothing but characters in the input. Order of the characters should not matter.

    0 讨论(0)
  • 2021-01-12 13:54

    You can make use of sets:

    >>> l = ['aba', 'acba', 'caz']
    >>> s = set('abc')
    >>> [item for item in l if not set(item).difference(s)]
    ['aba', 'acba']
    
    0 讨论(0)
  • 2021-01-12 13:55

    Assuming you only want the strings in your list which have only the characters in your search string, you can easily perform

    >>> hay = ['aba', 'acba', 'caz']
    >>> needle = set('abc')
    >>> [h for h in hay if not set(h) - needle]
    ['aba', 'acba']
    

    If you wan't to avoid sets, you can also do the same using str.translate. In this case, you are removing all characters which are in your search string.

    >>> needle = 'abc'
    >>> [h for h in hay if not h.translate(None,needle)]
    ['aba', 'acba']
    
    0 讨论(0)
  • 2021-01-12 13:55

    I will assume your reluctance for regexp is not really an issue :

    strings = ['aba', 'acba', 'caz']
    given = "abc"
    filter(lambda value: re.match("^[" + given + "]$", value), strings)
    
    0 讨论(0)
  • 2021-01-12 14:01

    Below is the code:

    a = ['aba', 'acba', 'caz']
    needle = 'abc'
    
    def onlyNeedle(word):
        for letter in word:
            if letter not in needle:
                return False
    
        return True
    
    a = filter(onlyNeedle, a)
    
    print a
    
    0 讨论(0)
提交回复
热议问题