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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • katyalrikin
    New Member
    • Sep 2014
    • 3

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

    Code:
    sent = raw_input()
    if sent.__contains__("S" or "I" or "H" or "X" or "O" or "N" or "Z"):
        print("YES")
    else:
        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?
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    You will need a loop to do that using the in keyword.
    Code:
    >>> if False in [c in sent for c in letterList]:
    ... 	print "No"
    ... else:
    ... 	print "Yes"
    ... 	
    No
    >>>

    Comment

    • dwblas
      Recognized Expert Contributor
      • May 2008
      • 626

      #3
      You can also use set difference and test for length
      Code:
      control_set=set(["S", "I", "H", "X", "O", "N", "Z"])
      test_set = set(["B", "S", "I", "H", "X", "O", "N", "Z", "A", "C"])
      result_set=test_set.difference(control_set)
      print result_set, len(result_set), "= False"
      
      test_set = set(["S", "I", "H", "X", "O", "O"])
      result_set=test_set.difference(control_set)
      print result_set, len(result_set), "= True"

      Comment

      Working...