首页 > 解决方案 > 如何检查2个字符串是否具有相同的字符?- Python

问题描述

我想检查 2 个字符串是否有相同的字符?

比如:
“aand”和“daan” => true
“aafw”和“kaaw” => false

这是我的代码:

def procedures(txt1, txt2):
    str1 = txt1.lower()
    str2 = txt2.lower()
    for i in str1:
        for j in str2:
            if i == j:
                str1.replace(i, "", 1)
                str2.replace(i, "", 1)
                print("did")
    if str1 == "" and str2 == "":
        return True
    else:
        return False

但它False返回aliiand liai

我所做的?

标签: pythonpython-3.x

解决方案


您可以像遍历列表/元组一样遍历 python 字符串。一个简单的功能是:

def stringCompare(a, b):
    for i in a:
        if i not in b:
            return False
        
    return True

print(stringCompare("aand", "daan"))
>> True

print(stringCompare("aafw", "kaaw"))
>> False

print(stringCompare("alii", "liai"))
>> True

请注意,上述函数仅检查两个字符串中的所有字符是否相等。现在,为了检查出现次数,您可以使用collectionsas:

from collections import Counter

def stringCompare2(a, b):
    # also compares the occurance
    occurance_dict_a = Counter(a)
    occurance_dict_b = Counter(b)
    
    return occurance_dict_a == occurance_dict_b

print(stringCompare2("abc", "aabc"))
>> False

print(stringCompare2("abc", "cba"))
>> True

推荐阅读