我尝试与字符串进行比较,两者都包含德语元音变音“ü”。两者看起来完全一样,也没有尾随 \n
或类似的内容。
其中一个位是从 xml 文件读取的,另一个位是从文件系统读取的。逐个字母地比较它们,显示出与元音变音的区别。
扭曲的元音变音(由两个字母、一个正常的 u 和两个上面的点组成)来自文件系统。我正在使用 macOS High Sierra 并运行 Python 3.7。使用 os.listdir() 读取文件名。
我很感激处理这种奇怪行为的建议(摆脱“ü”不是一个选择)。
最佳答案
不要直接比较字符串,而是在给定相同的 form
参数的情况下比较它们的 unicodedata.normalize
结果
来自文档:Comparing strings
A second tool is the unicodedata module’s normalize() function that converts strings to one of several normal forms, where letters followed by a combining character are replaced with single characters. normalize() can be used to perform string comparisons that won’t falsely report inequality if two strings use combining characters differently
import unicodedata
def compare_strs(s1, s2):
def NFD(s):
return unicodedata.normalize('NFD', s)
return NFD(s1) == NFD(s2)
关于python - 由于德语变音,Python 中的字符串不相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59892754/