我怎样才能在 Python 中做到这一点?
first string = GOOD MORNING
second string = GOOD BYE
5 个字符后没有匹配
在 C 中,它可以这样完成:
length = strspn(str1,str2);
我怎样才能在 Python 中做到这一点?
first string = GOOD MORNING
second string = GOOD BYE
5 个字符后没有匹配
在 C 中,它可以这样完成:
length = strspn(str1,str2);
为了多样性
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
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)
两种方法:
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
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
我不知道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
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
看起来像一份工作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