【问题标题】:Is there a pythonic way to count the number of leading matching characters in two strings?有没有一种pythonic方法来计算两个字符串中前导匹配字符的数量?
【发布时间】:2019-10-29 01:28:30
【问题描述】:

对于两个给定的字符串,是否有一种 Python 方法来计算两个字符串(从字符串的位置 0 开始)有多少连续字符相同?

例如在aaa_Helloaa_World 中,“前导匹配字符”是aa,长度为2。在anotherexample 中没有前导匹配字符,这将给出长度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


【解决方案1】:

您可以使用zipenumerate

def matchlen(str1, str2):
    i = -1 # needed if you don't enter the loop (an empty string)
    for i, (char1, char2) in enumerate(zip(str1, str2)):
        if char1 != char2:
            return i
    return i+1

【讨论】:

  • 嗨@S。佩莱格​​里诺,欢迎来到现场!谢谢您的回答。我猜对了,所有解决方案(Amadans,你的和我的)基本上都是一样的:循环遍历字符并计算匹配项?
【解决方案2】:
from itertools import takewhile
common_prefix_length = sum(
    1 for _ in takewhile(lambda x: x[0]==x[1], zip(string0, string1)))

zip 将两个字符串中的字母配对; takewhile 只要它们相等就会产生它们; sum 会看到有多少。

正如泡泡泡泡所说,这确实与您的循环事物完全相同。它唯一的优点(也是唯一的缺点)是它是单线的。随便拿吧。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-25
    • 2014-04-20
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    相关资源
    最近更新 更多