如何检查 python 中的 2 个字符串是否包含相同的字母和数字?

How to check if 2 strings contain same letters and numbers in python?

我想检查两个字符串是否包含相同的字母和数字

BUT忽略特殊字符,如_

示例:

word1 = "ABCD" , word2 = "ACDB"  => return True
word1 = "ABC1E_" , word2 = "AE1CB" => return True
word1 = "AB12" , word2 = "ABE2" => return False
word1 = "ABB" , word2 = "AB" => return True 

编辑:并在问题中进行了编辑,其中只有内容很重要,而不是数字的计数。因此,为了获得正确的结果,您应该切换到一组。并简单地列出被忽略的字符

ignored_chars = ['_']
s = set()
for letter in word:
    if letter in ignored_chars:
        continue
    s.add(letter)

并且仍然比较结果集。

from string import ascii_letters, digits


def compare_alphanumeric_membership(first, second):
    for character in first:
        if character in ascii_letters + digits and character not in second:
            return False
    return True


word1 = 'ABCD'
word2 = 'ACDB'
assert compare_alphanumeric_membership(word1, word2)

word1 = 'ABC1E_'
word2 = 'AE1CB'
assert compare_alphanumeric_membership(word1, word2)

word1 = 'AB12'
word2 = 'ABE2'
assert not compare_alphanumeric_membership(word1, word2)

word1 = 'ABB'
word2 = 'AB'
assert compare_alphanumeric_membership(word1, word2)

按照问题中列出的规格运行。

Process finished with exit code 0

假设您要考虑每个字符串中的每个字母数字字符都相同(不仅仅是字符集),您可以在过滤字符后比较 Counters。

from collections import Counter
res = Counter(filter(str.isalnum, word1)) == Counter(filter(str.isalnum, word2))

如果你只是想比较字符集,( "AAB"和"AB" 会 return true),您可以对 set

使用类似的方法
res = set(filter(str.isalnum, word1)) == set(filter(str.isalnum, word2))

以下函数将比较两个字符串。

from string import ascii_letters, digits

def cmp_strings(str1, str2):
    return all([i in str2 for i in str1 if i in ascii_letters + digits])

print cmp_strings('ABCD', 'ACDB_')
print cmp_strings('ABCD_', 'ACDB')
print cmp_strings('AB12', 'ABE2')
print cmp_strings('ABC1E_', 'AE1CB')

输出

True
True
False
True

这个呢?

set(word2).issubet(set(word1))