【发布时间】:2019-10-29 01:28:30
【问题描述】:
对于两个给定的字符串,是否有一种 Python 方法来计算两个字符串(从字符串的位置 0 开始)有多少连续字符相同?
例如在aaa_Hello 和aa_World 中,“前导匹配字符”是aa,长度为2。在another 和example 中没有前导匹配字符,这将给出长度0。
我已经编写了一个函数来实现这一点,它使用一个 for 循环,因此对我来说似乎很不合 Python:
def matchlen(string0, string1): # Note: does not work if a string is ''
for counter in range(min(len(string0), len(string1))):
# run until there is a mismatch between the characters in the strings
if string0[counter] != string1[counter]:
# in this case the function terminates
return(counter)
return(counter+1)
matchlen(string0='aaa_Hello', string1='aa_World') # returns 2
matchlen(string0='another', string1='example') # returns 0
【问题讨论】:
-
我不是来自 Python,但我是
for循环 unpythonic?您的函数看起来不错(至少对于非pythonic)。正则表达式不会有太大帮助。
标签: regex python-3.x string-matching string-length