8

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 i in str:
   if i in ['a','b','c']:
      pass
   else :
      print('wrong character')
Weafs.py
  • 22,731
  • 9
  • 56
  • 78
Jagoda
  • 424
  • 1
  • 5
  • 18

5 Answers5

8

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')
anon582847382
  • 19,907
  • 5
  • 54
  • 57
  • 3
    Note to the OP: You can check the contrary using `all` and removing the `not` : `all(c in ('a', 'b', 'c') for c in _str) -> True` –  Nov 02 '14 at 20:00
8

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)
georg
  • 211,518
  • 52
  • 313
  • 390
7

Using regular expressions:

import re
if re.search('[^abc]', string):
    print('wrong character')
Daniel
  • 42,087
  • 4
  • 55
  • 81
4

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

re.match('^[abc]+$', 'string')
wjandrea
  • 28,235
  • 9
  • 60
  • 81
DTK
  • 141
  • 3
1

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'):

Anzel
  • 19,825
  • 5
  • 51
  • 52