Check if a string contains only given characters

前端 未结 5 1486
北恋
北恋 2020-12-15 13:51

I\'m wondering if there is more elegant way to check if the string (str = \'abcccbbaabcbca\') contains only \'a\',\'b\' or \'c\' than iterating over it :

for         


        
相关标签:
5条回答
  • 2020-12-15 14:29

    Using regular expressions:

    import re
    if re.search('[^abc]', string):
        print('wrong character')
    
    0 讨论(0)
  • 2020-12-15 14:32

    Convert both strings to sets and check if they are equal. If yes, your string contains a AND b AND c:

    valid = set(your_string) == set('abc')...
    

    Use issubset to check if it contains ANY of a, b, c:

    valid = set(your_string) <= set('abc')
    

    or

    valid = set(your_string).issubset('abc')
    

    Subtract the sets to find out invalid characters:

    bad_chars = set('abcXYcba') - set('abc') # set(X,Y)
    
    0 讨论(0)
  • 2020-12-15 14:41

    Feel free to mock, since this jumps directly to a regular expression, but test for matching against "^[abc]+$"

    re.match('^[abc]+$', 'string')
    
    0 讨论(0)
  • 2020-12-15 14:46

    You could use any with a generator expression:

    if any(c not in 'abc' for c in _str):  # Don't use str as a name.
        print('Wrong character')
    
    0 讨论(0)
  • 2020-12-15 14:54

    You can also use string.translate:

    import string
    
    s = 'abcccbbaabcbca'
    # translate character to empty ""
    t = string.maketrans("","")
    
    # if non-abc character is found s.translate will become the bad characters
    if s.translate(t, 'abc'):
        print ('wrong character')
    

    Updated

    As also pointed out from @PadraicCunningham

    # for one off usage, you can skip making a translation table.

    if s.translate(None, 'abc'):

    0 讨论(0)
提交回复
热议问题