Return True if all characters in a string are in another string

后端 未结 2 908
攒了一身酷
攒了一身酷 2020-12-21 00:16

Alright so for this problem I am meant to be writing a function that returns True if a given string contains only characters from another given string. So if I input \"bird\

相关标签:
2条回答
  • 2020-12-21 00:30

    This is a perfect use case of sets. The following code will solve your problem:

    def only_uses_letters_from(string1, string2):
       """Check if the first string only contains characters also in the second string."""
       return set(string1) <= set(string2)
    
    0 讨论(0)
  • 2020-12-21 00:40

    sets are fine, but aren't required (and may be less efficient depending on your string lengths). You could also do simply:

    s1 = "bird"
    s2 = "irbd"
    
    print all(l in s1 for l in s2)  # True
    

    Note that this will stop immediately as soon as a letter in s2 isn't found in s1 and return False.

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