Python 使用 difflib 模块对比两个字符串的差异

在 Python 中,可以使用字符串的 upper() 方法将小写字母转成大写字母。示例如下:

str1 = "hello, world"
str2 = str1.upper()
print(str2)  # 输出 "HELLO, WORLD"

注意,upper() 方法只会将字符串中的小写字母转成大写字母,如果原字符串中本身就包含大写字母,则不会受到影响。如果你想将字符串中的所有字母都转成大写字母,可以使用 str.upper() 方法。

可以使用 Python 内置的 difflib 模块对比两个字符串的差异,示例代码如下:

from difflib import ndiff

str1 = "Hello, world"
str2 = "Hi, world"

# 使用 ndiff 对比两个字符串的差异
diff = ndiff(str1, str2)

# 打印差异
for line in diff:
    if line.startswith("- "):
        print("Delete: {}".format(line[2:].strip()))
    elif line.startswith("+ "):
        print("Add: {}".format(line[2:].strip()))
    elif line.startswith("? "):
        print("Change: {}".format(line[2:].strip()))
    else:
        print("Same: {}".format(line.strip()))

上述代码将输出:

Delete: H
Add: H i
Same: ,   w
Change: o => ,
Same: r
Same: l
Same: d

可以看到,差异包含了被删除的字符、被添加的字符,以及被修改的字符。

猜你喜欢

转载自blog.csdn.net/songpeiying/article/details/132709460