Test if string ONLY contains given characters

前端 未结 7 534
甜味超标
甜味超标 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 14:07

    The question is somewhat ambiguous about re-using letters from the base string. Or if there should or should not be repeats, or missing letters allowed. This solution addresses that with a function including a reuse parameter:

    from collections import Counter
    
    def anagram_filter(data, base, reuse=True):
        if reuse: # all characters in objects in data are in base, count ignored
            base = set(base)
            return [d for d in data if not set(d).difference(base)]
        r = []
        cb = Counter(base)
        for d in data:
            for k, v in Counter(d).iteritems():
                if (k not in cb.keys()) or (v > cb[k]):
                    break
            else:
                r.append(d)
        return r
    

    Usage:

    >>> anagram_filter(['aba', 'acba', 'caz'], 'abc')
    ['aba', 'acba']
    >>> anagram_filter(['aba', 'acba', 'caz'], 'abc', False)
    []
    >>> anagram_filter(['aba', 'cba', 'caz'], 'abc', False)
    ['cba']
    
    0 讨论(0)
提交回复
热议问题