[英]How do I compare two strings in python for differences?
I've got two strings like this:我有两个这样的字符串:
string1 = "Foo Bar"
string2 = "Foo BBar"
How do I compare them to see the difference?我如何比较它们以查看差异? If I just compare
string1[i]
to string2[i]
I just end up with the last Word "Bar" being different, as, for example, string1[5]
isn't the same as string2[5]
, and so on.如果我只是将
string1[i]
与string2[i]
进行比较,我最终会发现最后一个单词 "Bar" 不同,例如, string1[5]
与string2[5]
不同,依此类推.
Is there a way to just output "B"?有没有办法只使用 output “B”?
As suggested by @barmar, difflib
may be the way to go here.正如@barmar 所建议的,
difflib
可能是 go 的方式。
So here's a snippet just to fit your example, but it may not be suited for all your cases.所以这里有一个片段只是为了适合你的例子,但它可能并不适合你的所有情况。
import difflib
string1 = "Foo Bar"
string2 = "Foo BBar"
[d[2:] for d in difflib.ndiff(string1, string2) if d.startswith("+")]
# ['B']
If you want to know more about it, please read the doc or this answer .如果您想了解更多信息,请阅读文档或此答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.