Python 计算用户提供的两个输入之间的匹配字符

Python 计算用户提供的两个输入之间的匹配字符,python,count,match,Python,Count,Match,如何获得这个python输出?计算匹配和不匹配 String1:aaabbbccc#aaabbbccc是用户输入 String2:aabbbcccc#aabbbcccc是用户输入 匹配项:? 不匹配:? 第1条:aaAbbBccc#不匹配为大写 String2:aaBbbCccc您可以尝试以下方法 >>> s1 = 'aaabbbccc' >>> s2 = 'aabbbcccc' >>> match = 0 >>> mism

如何获得这个python输出?计算匹配和不匹配

String1:aaabbbccc#aaabbbccc是用户输入
String2:aabbbcccc#aabbbcccc是用户输入

匹配项:?
不匹配:?
第1条:aaAbbBccc#不匹配为大写

String2:aaBbbCccc

您可以尝试以下方法

>>> s1 = 'aaabbbccc'
>>> s2 = 'aabbbcccc'
>>> match = 0
>>> mismatch = 0
>>> for i,j in itertools.izip_longest(s1,s2):
        if i == j:
            match += 1
        else:
            mismatch +=1
在python3中,使用而不是
itertools.izip\u longest
。 如果想考虑<代码> < <代码> >代码> < <代码>为匹配,则将IF条件更改为

if i.lower() == j.lower():

最后从变量
match
mismatch

中获取匹配和不匹配计数假设您从文件或用户输入中获取了字符串,那么:

import itertools

s1 = 'aaabbbccc'
s2 = 'aabbbcccc'

# This will only consider n characters, where n = min(len(s1), len(s2))
match_indices = [i for (i,(c1, c2)) in enumerate(itertools.izip(s1, s2)) if c1 == c2]
num_matches   = len(match_indices)
num_misses    = min(len(s1), len(s2)) - num_matches

print("Matches:    %d" % num_matches)
print("Mismatches: %d" % num_misses)
print("String 1:   %s" % ''.join(c if i in match_indices else c.upper() for (i,c) in enumerate(s1)))
print("String 2:   %s" % ''.join(c if i in match_indices else c.upper() for (i,c) in enumerate(s2)))
输出:

Matches: 7 Mismatches: 2 String 1: aaAbbBccc String 1: aaBbbCccc 这将产生:

Matches: 7
Mismatches: 2
String 1: aaAbbBccc
String 2: aaBbbCccc
您可以尝试:

    index = 0
    for letter in String1:
        if String1[index] != String2[index]:
            mismatches +=1
    index += 1
print "Matches:" + (len(String1)-mismatches)
print "Mismatches:" + mismatches  

字符数是否相同?用户可以输入任意数量的字符。@SamyShrestha如果输入为“abcd”和“abcdefghijklmnop”,则预期的输出是什么?我想学习这一点。。我不知道如何计算匹配和不匹配。。所以我试着在python库中搜索。但是没有找到任何东西。提示:
zip
,或者可能是
itertools.izip\u longest
…是否有一个循环类型行被忽略了?实际上这就像输入用户输入后一样。程序要求输入(添加索引)d(删除索引)s(分数)q(退出):s当输入“s”时,它会给出所需的信息作为输出
Matches: 7
Mismatches: 2
String 1: aaAbbBccc
String 2: aaBbbCccc
    index = 0
    for letter in String1:
        if String1[index] != String2[index]:
            mismatches +=1
    index += 1
print "Matches:" + (len(String1)-mismatches)
print "Mismatches:" + mismatches  
>>>s= list('aaabbbccc')
>>>s1=list('aabbbcccc')
>>>match=0
>>>mismatch=0
>>>for i in range(0,len(s)):
...     if(s[i]==s1[i]):
...             match+=1
...     else:
...             mismatch+=1
...             s[i]=s[i].upper()
...             s1[i]=s1[i].upper()
>>>print 'Matches:'+ str(match)
>>>print 'MisMatches:'+str(mismatch)
>>>print 'String 1:' +''.join(s)
>>>print 'String 2:' +''.join(s1)