Python uses the difflib module to compare the differences between two strings

In Python, you can use the string upper()method to convert lowercase letters to uppercase letters. Examples are as follows:

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

Note that upper()the method only converts lowercase letters in the string to uppercase letters. If the original string itself contains uppercase letters, it will not be affected. If you want to convert all letters in the string to uppercase, you can use str.upper()the method.

You can use Python's built-in difflib module to compare the differences between two strings. The sample code is as follows:

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()))

The above code will output:

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

As you can see, the difference includes deleted characters, added characters, and modified characters.

Guess you like

Origin blog.csdn.net/songpeiying/article/details/132709460