在另一个程序的 python 3 字符串中,ü 是两个字符,u 和 umlaut。为什么会这样?[重复]

问题描述 投票:3回答:1

我从一个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 和 umlaut 是分开的? 如果我在这个字符串中输入一个ü,它被读作'ü',并且'ü'的测试成功。 我怎样才能纠正这个字符串,使它有一个ü而不是两个独立的字符?

先谢谢大家的提示。 我搜索了一下,没有发现任何有用的信息。

python character-encoding diacritics
1个回答
2
投票

字符串中的字符和条件中的字符有不同的表示方式。

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
© www.soinside.com 2019 - 2024. All rights reserved.