Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
725 views
in Technique[技术] by (71.8m points)

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

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").

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...