返回True如果字符串中的所有字符在另一个字符串 [英] Return True if all characters in a string are in another string

查看:162
本文介绍了返回True如果字符串中的所有字符在另一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,所以对于这个问题,我的意思被写一个给定的字符串包含从另一个给定的字符串中的字符,则返回true的函数。所以,如果我输入鸟作为第一个字符串,irbd作为第二个,它会返回True,但如果我用鸟作为第一个字符串,IRDB作为第二个它会返回False。我的code到目前为止是这样的:

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

当我尝试如果字符串中完全相同的顺序,或者运行它仅返回True剧本我只输入一个字母(鸟或b和鸟与鸟和IRDB )。

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

推荐答案

这是的的。下面code将解决你的问题:

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)

这篇关于返回True如果字符串中的所有字符在另一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆