Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 732
lilbanili Avatar asked Mar 11 '15 20:03

lilbanili


People also ask

How to check if a string contains all characters of another string?

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.

How do I check if a string contains alphanumeric characters?

The isalnum () method returns True if all characters in the string are alphanumeric (either alphabets or numbers). If not, it returns False. No parameters.

Do two strings contain the same characters in same order?

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.

What is the difference between isalnum () and return true and false?

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.


1 Answers

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)
like image 103
Ceasar Bautista Avatar answered Oct 20 '22 01:10

Ceasar Bautista