Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string contains only given characters

Tags:

python

string

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')
like image 901
AirelleJab Avatar asked Nov 02 '14 19:11

AirelleJab


2 Answers

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')
like image 155
anon582847382 Avatar answered Oct 04 '22 00:10

anon582847382


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)
like image 38
georg Avatar answered Oct 03 '22 23:10

georg