我怎样才能在Python中执行此操作?
first string = GOOD MORNING
second string = GOOD BYE
5个字符后没有匹配
在C中,它可以完成:
length = strspn(str1,str2);
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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
答案 3 :(得分: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)
答案 4 :(得分: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
答案 5 :(得分: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
答案 6 :(得分: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