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

时间:2016-06-14 09:48:17

标签: python string string-comparison

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

但是忽略特殊字符,例如_

示例:

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

5 个答案:

答案 0 :(得分:4)

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

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

如果你只是想比较一组字符,( ie “AAB”和“AB”将返回true ),你可以使用与set

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

这是怎么回事?

ReferenceError: True is not defined

答案 4 :(得分:-1)

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

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

仍然比较结果集。