python - 如何在 Python 中将字符串转换为 utf-8

我有一个将 utf-8 字符发送到我的 Python 服务器的浏览器,但是当我从查询字符串中检索它时,Python 返回的编码是 ASCII。如何将纯字符串转换为 utf-8?

注意:从网络传递过来的字符串已经是 UTF-8 编码的,我只是想让 Python 将其视为 UTF-8 而不是 ASCII。

最佳答案

在 Python 2 中

>>> plain_string = "Hi!"
>>> unicode_string = u"Hi!"
>>> type(plain_string), type(unicode_string)
(<type 'str'>, <type 'unicode'>)

^ 这是字节字符串(plain_string)和unicode字符串的区别。

>>> s = "Hello!"
>>> u = unicode(s, "utf-8")

^ 转换为 unicode 并指定编码。

在 Python 3 中

所有字符串都是 unicode。 unicode 函数不再存在。查看@Noumenon 的回答

https://stackoverflow.com/questions/4182603/

相关文章:

linux - 在 bash 中创建临时文件

c - 写入 .txt 文件?

python - 我可以单独使用 Flask app.run() 为多个客户端提供服务吗?

c - 在 Linux 中测量时间 - 时间 vs 时钟 vs getrusage vs clock

python - 如何在 Python 中直接获取字典键作为变量(而不是通过从值中搜索)?

linux - 如何在 Apache 服务器上自动将 HTTP 重定向到 HTTPS?

python - Argparse:在 "optional arguments"下列出的必需参数?

linux - 如何打印 ld(linker) 搜索路径

python - 如何编写好的/正确的包 __init__.py 文件

python - 从 django 的查询集中获取第一个对象的最快方法?