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

拜拜、爱过 提交于 2020-01-20 08:12:38

问题


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" as the first string and "irbd" as the second, it would return True, but if I used "birds" as the first string and "irdb" as the second it would return False. My code so far 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 the script it only returns True if the strings are in the exact same order or if I input only one letter ("bird" or "b" and "bird" versus "bird" and "irdb").


回答1:


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)



回答2:


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.



来源:https://stackoverflow.com/questions/28997056/return-true-if-all-characters-in-a-string-are-in-another-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!