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").
There are numerous ways to check if a string contains all characters of another string. But for the sake of simplicity, we will use split () method, toLowerCase () method, include () method, every () method and ternary operator (?) to accomplish our goal.
The isalnum () method returns True if all characters in the string are alphanumeric (either alphabets or numbers). If not, it returns False. No parameters.
Given two strings s1 and s2, the task is to find whether the two string contain the same characters that occur in the same order. For example: string “Geeks” and string “Geks” contain the same characters in same order. Recommended: Please try your approach on {IDE} first, before moving on to the solution.
Returns True if all characters in the string are alphanumeric and returns False even if one character is not alphanumeric. The following example demonstrates isalnum () method. The isalnum () method will return False if the string consists of whitespaces and symbols.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With