为什么使用 python split 时字符串会发生变化?

2023-12-09

test_str = "Question: The cryptocurrency Bitcoin Cash (BCH/USD) settled at 1368 USD at 07:00 AM UTC at the Bitfinex exchange on Monday, April 23. In your opinion, will BCH/USD trade above 1500 USD (+9.65%) at anу timе bеfore Арril 28? Indicаtоr: 60.76%"

print(test_str)
print(test_str.split('before '))

这是分割后得到的输出

"['Question: The cryptocurrency Bitcoin Cash (BCH/USD) settled at 1368 USD at 07:00 AM UTC at the Bitfinex exchange on Monday, April 23. In your opinion, will BCH/USD trade above 1500 USD (+9.65%) at an\xd1\x83 tim\xd0\xb5 b\xd0\xb5fore \xd0\x90\xd1\x80ril 28? Indic\xd0\xb0t\xd0\xber: 60.76%']"

Demo: https://repl.it/repls/VitalOrganicBackups


该问题是由拉丁字符和西里尔字符混合引起的。它们在大多数保单中打印完全相同,但仍然是不同的字符并且具有不同的代码。

问题中的输出适用于 Python 2.7(原始提问者使用的是什么),但在 Python 3 中很容易具有等效的行为:

>>> print(test_str.encode('UTF8'))
b'Question: The cryptocurrency Bitcoin Cash (BCH/USD) settled at 1368 USD at 07:00 AM UTC at the Bitfinex exchange on Monday, April 23. In your opinion, will BCH/USD trade above 1500 USD (+9.65%) at an\xd1\x83 tim\xd0\xb5 b\xd0\xb5fore \xd0\x90\xd1\x80ril 28? Indic\xd0\xb0t\xd0\xber: 60.76%'

unicodedata 模块有助于更好地理解实际发生的情况:

>>> for i in b'\xd1\x83\xd0\xb5\xd0\x90\xd1\x80\xd0\xbe'.decode('utf8'):
    print(i, hex(ord(i)), i.encode('utf8'), unicodedata.name(i))
у 0x443 b'\xd1\x83' CYRILLIC SMALL LETTER U
е 0x435 b'\xd0\xb5' CYRILLIC SMALL LETTER IE
А 0x410 b'\xd0\x90' CYRILLIC CAPITAL LETTER A
р 0x440 b'\xd1\x80' CYRILLIC SMALL LETTER ER
о 0x43e b'\xd0\xbe' CYRILLIC SMALL LETTER O

因此,原始文本包含西里尔字母,为了比较,它们与拉丁字母不同,即使它们打印相同。该问题与 split 无关,只是原始字符串很差。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么使用 python split 时字符串会发生变化? 的相关文章

随机推荐