Return True if all characters in the string are on another string

Ok, so for this task I have to write a function that returns True if the given string contains only characters from another given string. Therefore, if I enter “bird” as the first line, and “irbd” as the second, it will return True, but if I used “birds” as the first line, and irdb as the second, it would return False. My code looks like this:

def only_uses_letters_from(string1,string2):
"""Takes two strings and returns true if the first string only contains characters also in the second string.

string,string -> string"""
if string1 in string2:
    return True
else:
    return False

When I try to run a script, it returns True only if the lines are in the same order or I entered only one letter ("bird" or "b" and "bird" versus "bird" and "bird") IBRD ").

+4
source share
2 answers

This is an ideal use case for sets . The following code will help 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)
+9
source

sets are good, but not required (and may be less efficient depending on the length of your string). You can also do the following:

s1 = "bird"
s2 = "irbd"

print all(l in s1 for l in s2)  # True

Please note that this will stop immediately as soon as the letter in is s2not found in s1and returns False.

+4
source

All Articles