Python,转换4byte char以避免MySQL错误“字符串值不正确:”

2024-10-01 17:28:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要将一个4字节的字符转换成其他字符。这是为了将它插入到我的utf-8mysql数据库中,而不会得到诸如“不正确的字符串值:'\xF0\x9F\x94\x8E'对于第1行的列'line'”

Warning raised by inserting 4-byte unicode to mysql表示要这样做:

>>> import re
>>> highpoints = re.compile(u'[\U00010000-\U0010ffff]')
>>> example = u'Some example text with a sleepy face: \U0001f62a'
>>> highpoints.sub(u'', example)
u'Some example text with a sleepy face: '

但是,我在注释中得到了与用户相同的错误,“…坏字符范围…”这显然是因为我的Python是UCS-2(不是UCS-4)构建的。但我不清楚该怎么做?在


Tags: 字符串textre数据库字节examplewithsome
1条回答
网友
1楼 · 发布于 2024-10-01 17:28:01

在UCS-2构建中,python在内部为\U0000ffff代码点上的每个unicode字符使用2个代码单元。正则表达式需要使用这些表达式,因此需要使用以下正则表达式来匹配它们:

highpoints = re.compile(u'[\uD800-\uDBFF][\uDC00-\uDFFF]')

这个正则表达式匹配用UTF-16代理项对编码的任何代码点(参见UTF-16 Code points U+10000 to U+10FFFF)。在

要使其在Python UCS-2和UCS-4版本之间兼容,可以使用try:/except来使用其中一个:

^{pr2}$

UCS-2 python构建演示:

>>> import re
>>> highpoints = re.compile(u'[\uD800-\uDBFF][\uDC00-\uDFFF]')
>>> example = u'Some example text with a sleepy face: \U0001f62a'
>>> highpoints.sub(u'', example)
u'Some example text with a sleepy face: '

相关问题 更多 >

    热门问题