The Python Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: RPG Blues Looping

--

Chapters
00:00 Return True If All Characters In A String Are In Another String
00:37 Accepted Answer Score 14
00:52 Answer 2 Score 5
01:11 Thank you

--

Full question
https://stackoverflow.com/questions/2899...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #string #boolean

#avk47



ACCEPTED ANSWER

Score 14


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)



ANSWER 2

Score 5


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.