gpt4 book ai didi

指向结果的 Python 字符串比较

转载 作者:太空宇宙 更新时间:2023-11-03 12:14:32 24 4
gpt4 key购买 nike

我正在尝试比较 2 个 1000 字节的字符串,并想知道差异的确切开始位置,即;字符串从哪个字节开始不同..有什么函数可以判断吗?

最佳答案

也许使用 next 加一个生成器?

next(idx for idx,c in enumerate(your_string1) if c != your_string2[idx])

这将为您提供差异开始的索引,并在它们相等时引发 StopIteration

itertools.izip 甚至可能更优雅:

next(idx for idx,(c1,c2) in enumerate(izip(s1,s2)) if c1 != c2)

例子:

>>> from itertools import izip
>>> s1 = 'stop at the bus'
>>> s2 = 'stop at the car'
>>> next(idx for idx,(c1,c2) in enumerate(izip(s1,s2)) if c1 != c2)
12
>>> s1[12]
'b'
>>> s2[12]
'c'

关于指向结果的 Python 字符串比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12840451/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com