The Python Oracle

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

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC D Schuberts Piano Sonata D 850 in D

--

Chapters
00:00 Question
00:58 Accepted answer (Score 10)
01:17 Answer 2 (Score 4)
01:44 Thank you

--

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

Accepted answer links:
[sets]: https://docs.python.org/2/tutorial/datas...

--

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.