Python returns 单个非 ascii 字符串的长度为 2
Python returns length of 2 for single non-ascii character string
我正在尝试获取字符串中所选单词的跨度。使用 İ
字符时,我注意到 Python
的以下行为:
len("İ")
Out[39]: 1
len("İ".lower())
Out[40]: 2
# when `upper()` is applied, the length stays the same
len("İ".lower().upper())
Out[41]: 2
为什么同一个字符的大小写值长度不同(我觉得很confusing/undesired)?
有谁知道是否还有其他角色会发生这种情况?
谢谢!
编辑:
另一方面,例如Î
长度保持不变:
len('Î')
Out[42]: 1
len('Î'.lower())
Out[43]: 1
我认为问题在于该符号的小写字符在 ASCII 中未定义。
.lower()
函数可能对与字符关联的 ASCII 数字执行固定偏移,因为它适用于英文字母表。
那是因为小写的'İ'
是'i̇'
,有2个字符
>>> import unicodedata
>>> unicodedata.name('İ')
'LATIN CAPITAL LETTER I WITH DOT ABOVE'
>>> unicodedata.name('İ'.lower()[0])
'LATIN SMALL LETTER I'
>>> unicodedata.name('İ'.lower()[1])
'COMBINING DOT ABOVE'
一个字符是一个组合点,您的浏览器可能会在呈现时与最后一个引号重叠,因此您可能看不到它。但是如果你将它复制粘贴到你的 python 控制台,你应该能够看到它。
如果你尝试:
print('i̇'.upper())
你应该得到
İ
我正在尝试获取字符串中所选单词的跨度。使用 İ
字符时,我注意到 Python
的以下行为:
len("İ")
Out[39]: 1
len("İ".lower())
Out[40]: 2
# when `upper()` is applied, the length stays the same
len("İ".lower().upper())
Out[41]: 2
为什么同一个字符的大小写值长度不同(我觉得很confusing/undesired)?
有谁知道是否还有其他角色会发生这种情况? 谢谢!
编辑:
另一方面,例如Î
长度保持不变:
len('Î')
Out[42]: 1
len('Î'.lower())
Out[43]: 1
我认为问题在于该符号的小写字符在 ASCII 中未定义。
.lower()
函数可能对与字符关联的 ASCII 数字执行固定偏移,因为它适用于英文字母表。
那是因为小写的'İ'
是'i̇'
,有2个字符
>>> import unicodedata
>>> unicodedata.name('İ')
'LATIN CAPITAL LETTER I WITH DOT ABOVE'
>>> unicodedata.name('İ'.lower()[0])
'LATIN SMALL LETTER I'
>>> unicodedata.name('İ'.lower()[1])
'COMBINING DOT ABOVE'
一个字符是一个组合点,您的浏览器可能会在呈现时与最后一个引号重叠,因此您可能看不到它。但是如果你将它复制粘贴到你的 python 控制台,你应该能够看到它。
如果你尝试:
print('i̇'.upper())
你应该得到
İ