在来自另一个程序的 python 3 字符串中,ü 是两个字符,即 u 和元音变音。为什么?

in a python 3 string from another program, ü is two characters, the u and the umlaut. Why?

我正在从 php 7 程序中获取一个字符串,并在 Python 3.7.2 中处理它。

my_str = 'ü'

print(type(my_str))

str_list = list(my_str)

for letter in str_list:
    print('letter',letter)

if 'ü' in my_str:
    print('we have the umlaut')
else:
    print('we have no umlaut')

这是输出:

<class 'str'>
letter u
letter ̈
we have no umlaut

为什么字母 u 与变音符号分开?如果我在此字符串中键入一个 ü,它将被读作“ü”,并且“ü”的测试成功。我如何更正此字符串,使其包含一个 ü 而不是两个单独的字符?

提前感谢您提供任何提示。我已经搜索过这个但没有找到任何有用的东西。

你的字符串中的字符和你条件中的字符有不同的表示:

from unicodedata import name, normalize


my_str = 'ü'
for c in my_str:
    print(name(c))

# LATIN SMALL LETTER U
# COMBINING DIAERESIS

your_u = 'ü'  # copy pasted from your 'if ...' line
for c in your_u:
    print(name(c))

# LATIN SMALL LETTER U WITH DIAERESIS

您可以规范化您的字符串:

my_normalized_str = normalize('NFC', my_str)

for c in my_normalized_str:
    print(name(c))

#LATIN SMALL LETTER U WITH DIAERESIS

现在您的比较将按预期进行:

if 'ü' in my_normalized_str:
    print('we have the umlaut')
else:
    print('we have no umlaut')

# we have the umlaut