比较字符串python中的字符

时间:2016-04-06 15:29:10

标签: python string character string-comparison

我试图比较两个单独字符串中的字符,我的想法是我将返回一个值,该值对应于字符串共享的字符数。例如,如果第一个字符串是' mouse'和字符串2是'#house;#39;。他们将分享4/5个字符。重要的是要注意,如果角色处于相同的索引位置,他们只共享一个角色'

def compareWords(word1, word2):
result = 0
if word1[0] in word2[0]:
    result += 1
if word1[1] in word2[1]:
    result += 1
if word1[2] in word2[2]:
    result += 1
if word1[3] in word2[3]:
    result += 1
if word1[4] in word2[4]:
    result += 1
if word1[5] in word2[5]:
    result += 1
    print result, '/5'

working result

non-working result

2 个答案:

答案 0 :(得分:5)

zipsum

a,b = "house", "mouse"

print(sum(s1 == s2 for s1, s2 in zip(a, b)))
4
压缩将对同一个索引处的字符进行配对,然后总结s1 == s2将给出匹配字符计数的次数:

In [1]: a,b = "house", "mouse"

In [2]: zip(a, b)
Out[2]: [('h', 'm'), ('o', 'o'), ('u', 'u'), ('s', 's'), ('e', 'e')]

唯一不清楚的是,如果字符串长度不同,则用作 的内容。

如果您确实想要匹配和总和,您仍然可以使用相同的逻辑:

def paired(s1, s2):
    sm, index_ch = 0, []
    for ind, (c1, c2) in enumerate(zip(s1, s2)):
        if c1 == c2:
            sm += 1
            index_ch.append((ind, c1))
    return index_ch, sm

index_char, sm = paired("house", "mouse")

print(index_char, sm)

输出:

([(1, 'o'), (2, 'u'), (3, 's'), (4, 'e')], 4)

答案 1 :(得分:1)

如果要保留匹配的位置和字符,可以枚举字符串,然后计算生成的元组的集合的交集。如果您不想保留有关比赛性质的任何信息,我认为Padraic的答案更好。

演示:

>>> s1 = 'hello world'
>>> s2 = 'xelxx worxx'
>>> same = set(enumerate(s1)).intersection(enumerate(s2))
>>> same
set([(7, 'o'), (2, 'l'), (1, 'e'), (8, 'r'), (6, 'w'), (5, ' ')])
>>> len(same)
6
相关问题