By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,807 Members | 1,492 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,807 IT Pros & Developers. It's quick & easy.

How to check if string is made up of only certain letters

P: 3
Expand|Select|Wrap|Line Numbers
  1. sent = raw_input()
  2. if sent.__contains__("S" or "I" or "H" or "X" or "O" or "N" or "Z"):
  3.     print("YES")
  4. else:
  5.     print("NO")
This is what I have. If each letter in sent is in that list, print YES else print NO. But as long as i have 1 from the list it prints YES. That is not what I want. How can i fix this?
Oct 7 '14 #1
Share this Question
Share on Google+
2 Replies

Expert Mod 2.5K+
P: 2,851
You will need a loop to do that using the in keyword.
Expand|Select|Wrap|Line Numbers
  1. >>> if False in [c in sent for c in letterList]:
  2. ...     print "No"
  3. ... else:
  4. ...     print "Yes"
  5. ...     
  6. No
  7. >>>
Oct 8 '14 #2

Expert 100+
P: 621
You can also use set difference and test for length
Expand|Select|Wrap|Line Numbers
  1. control_set=set(["S", "I", "H", "X", "O", "N", "Z"])
  2. test_set = set(["B", "S", "I", "H", "X", "O", "N", "Z", "A", "C"])
  3. result_set=test_set.difference(control_set)
  4. print result_set, len(result_set), "= False"
  6. test_set = set(["S", "I", "H", "X", "O", "O"])
  7. result_set=test_set.difference(control_set)
  8. print result_set, len(result_set), "= True" 
Oct 8 '14 #3

Post your reply

Sign in to post your reply or Sign up for a free account.