在Python(2.7.3)中,如果str(x)中的任何字符都在str(y)中(或str(y)在str(x)中),如何编写一个能够回答的函数?

时间:2013-12-05 06:58:31

标签: python string python-2.7 user-defined-functions

def char_check(x,y):

    if (str(x) in y or x.find(y) > -1) or (str(y) in x or y.find(x) > -1):

        return True

    else:

        return False

print "You will enter two words that you think use some of the same letters."

x = raw_input('Enter one of the words: ')

y = raw_input('Enter the other word: ')

print char_check(x,y)

我想要做的是输入两个字符串,例如str(x)的“可怕”和str(y)的“bile”并返回“True”,因为字符'b','i',' l'和'e'由两个字符串共享。

我是新人并且正在努力学习,但我似乎无法自己解决这个问题。谢谢你们。

2 个答案:

答案 0 :(得分:4)

套几乎肯定是要走的路。

>>> set1 = set("terrible")
>>> set2 = set("bile")
>>> set1.issubset(set2)
False
>>> set2.issubset(set1)  # "bile" is a subset of "terrible"
True
>>> bool(set1 & set2)  # at least 1 character in set1 is also in set2
True

答案 1 :(得分:2)

试试这个 -

def char_check(x,y):
    if set(x) & set(y):
        return True
    else:
        return False