-3

我怎样才能在 Python 中做到这一点?

first string = GOOD MORNING
second string = GOOD BYE

5 个字符后没有匹配

在 C 中,它可以这样完成:

length = strspn(str1,str2);
4

7 回答 7

2

为了多样性

from itertools import takewhile, izip
sum(1 for x in takewhile(lambda x: x[0] == x[1], 
   izip(iter('GOOD MORNING'), iter('GOOD BYE'))))
5
于 2013-08-31T06:16:50.367 回答
1
def strspn(s1, s2):
    m = min(len(s1), len(s1))
    mismatches = (i for i, (c1, c2)
                  in enumerate(zip(s1[:m], s2[:m])) if c1 != c2)
    return next(mismatches, m)
于 2013-08-31T14:33:18.447 回答
1

两种方法:

first = 'GOOD MORNING'
second = 'GOOD BYE'

import difflib
sq = difflib.SequenceMatcher(None,first,second)
m = min(len(first),len(second))
print sq.find_longest_match(0,m,0,m)[2]

print '-----------'

print (i for i in xrange(min(len(first),len(second)))
       if first[i]!=second[i]).next()

结果

5
-----------
5
于 2013-08-31T08:20:59.537 回答
1
def matcher(A, B):
    for i in range(min(len(A), len(B))):
        if A[i] != B[i]:
            return i
    return min(len(A), len(B))

print str(matcher("GOOD MORNING", "GOOD BYE")) + " characters match"

def strspn(A, B):
    for i in range(len(A)):
        if A[i] not in B:
            return i
    return len(A)

print "129th has " + str(strspn("129th", "0123456789")) + " digits"

输出

5 characters match
129th has 3 digits
于 2013-08-31T06:08:41.130 回答
0

我不知道python是否有内置函数,但你可以简单地写你的

first = 'GOOD MORNING'
second = 'GOOD BYE'
len1 = len(first)
len2 = len(second)
count = 0
for i in range(len1):
    if i < len2 and first[i] == second[i]:
        count += 1
        continue
    else:
        break
return count
于 2013-08-31T06:17:55.803 回答
0
a = "good morning"
b = "good bye"


differ_idx = None
for idx, a_b in enumerate(zip(a, b)):
    a, b = a_b
    if a != b:
        differ_idx = idx
        break

print "first string = %r" % a
print "second string = %r" % b
if differ_idx is None:
    print "Strings match"
else:
    print "After %d characters there is no match" % differ_idx
于 2013-08-31T06:22:47.223 回答
0

看起来像一份工作enumerate

>>> a = "GOOD MORNING"
>>> b = "GOOD BYE"
>>> temp = max(a, b)
>>> for x, y in enumerate(min(a, b)):
...     if temp[x] != y:
...             print x
...             break
... 
5
于 2013-08-31T06:14:01.303 回答