比较字符串中的字符python

Rhy*_*ddy 3 python string character string-comparison

我正在尝试比较2个单独字符串中的字符,这个想法是我将返回一个值,该值对应于两个字符串共享多少个字符。例如,如果字符串1是“ mouse”,而字符串2是“ house”。他们将共享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'
Run Code Online (Sandbox Code Playgroud)

工作成果

非工作结果

Pad*_*ham 5

邮编总和

a,b = "house", "mouse"

print(sum(s1 == s2 for s1, s2 in zip(a, b)))
4
Run Code Online (Sandbox Code Playgroud)

压缩将在相同索引处将字符配对,然后求和多少次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')]
Run Code Online (Sandbox Code Playgroud)

唯一不清楚的是如果字符串的长度不同,您将使用什么。

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

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)
Run Code Online (Sandbox Code Playgroud)

输出:

([(1, 'o'), (2, 'u'), (3, 's'), (4, 'e')], 4)
Run Code Online (Sandbox Code Playgroud)