清理 UTF-8 编码字符串

发布于 2024-12-22 21:34:19 字数 259 浏览 4 评论 0原文

我想在将 UTF-8 编码的字符串用作 MySQL SELECT 语句的一部分之前对其进行清理。

例如,我有:

query = MySQLdb.escape_string(query)

但这行会导致引发异常,内容为

“ascii”编解码器无法对位置 0-2 中的字符进行编码:序号不在 范围(128)。

我该如何处理这个问题?

I want to sanitise a UTF-8 encoded string before using it as part of a MySQL SELECT statement.

For example, I have:

query = MySQLdb.escape_string(query)

but this line is leading to a raised exception that reads

'ascii' codec can't encode characters in position 0-2: ordinal not in
range(128).

How can I handle this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

姜生凉生 2024-12-29 21:34:19

看起来 MySQLdb 正在尝试将您的 unicode 查询编码为字符串。为此,它使用默认编码:ASCII。

现在,您的输入无法编码为 ASCII,因此您只需告诉 python 它应该使用什么编码:utf-8。

您可以使用 query = query.encode('utf-8') 来实现此目的。

Looks like MySQLdb is trying to encode your unicode query to a string. To do so it's using the default encoding: ASCII.

Now, your input can't be encoded into ASCII, so you just need to tell python what encoding it should use: utf-8.

You can achieve this by using query = query.encode('utf-8').

夏日浅笑〃 2024-12-29 21:34:19

在您的示例中,query 的类型为“str”。如果在字符串前面加上“u”,它就会成为“unicode”类型。

>>> query = "こうえん"
>>> print type(query)
<type 'str'>
>>> query = u"こうえん"
>>> print type(query)
<type 'unicode'>

这是 Python 2.x 和 3.x 版本之间的主要区别之一。从 3.0 开始,所有字符串默认都是“unicode”。

In your example query is of type 'str'. If you put a 'u' before the string, it becomes of type 'unicode'.

>>> query = "こうえん"
>>> print type(query)
<type 'str'>
>>> query = u"こうえん"
>>> print type(query)
<type 'unicode'>

This is one of the main differences between Python versions 2.x and 3.x. Starting in 3.0, all strings are 'unicode' by default.

旧时模样 2024-12-29 21:34:19
query = "こうえん"
query = MySQLdb.escape_string(unicode(query,'utf-8'))
query = "こうえん"
query = MySQLdb.escape_string(unicode(query,'utf-8'))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文