python - 在 Python 中对字符串进行编码

标签 python python-2.7 utf-8 encode arabic

我想在终端上运行我的代码,但它显示了这个错误:

SyntaxError: Non-ASCII character '\xd8' in file streaming.py on line 72, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for detail

我尝试使用以下方法对阿拉伯字符串进行编码:

# -*- coding: utf-8 -*-

st = 'المملكة العربية السعودية'.encode('utf-8')

在终端上运行它对我来说非常重要,所以我不能使用IDLE。

最佳答案

问题是,由于您直接将字符粘贴到 python 文件中,解释器 (Python 2) 尝试将它们读取为 ASCII(即使在编码之前,它也需要定义文字),这是非法的。如果粘贴非 ASCII 字节,您需要的是 unicode 文字:

x=u'المملكة العربية السعودية' #Or whatever the corresponding bytes are
print x.encode('utf-8')

您还可以尝试将整个源文件设置为utf-8读取:

#/usr/bin/python
# -*- coding: utf-8 -*-

并且不要忘记使其可运行,最后,您可以从 Python 3 导入 future:

from __future__ import unicode_literal

位于文件顶部,因此默认情况下字符串文字为 utf-8。请注意,\xd8 在我的终端中显示为 phi,因此请确保编码正确。

关于python - 在 Python 中对字符串进行编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50438606/

相关文章:

python - 使用 Python 的简单 'chat' UDP 客户端和服务器,不能使用 `str` 作为 `send()` 有效载荷

+-* 的 python 压缩函数

python - 为什么这会返回 False

python - 为大对象分配名称似乎会大大增加内存使用量

tkinter - 使用 Tkinter 设置菜单小部件的宽度

python - 使用子进程延迟执行命令

python - 如何使用正则表达式 Python 在文件中查找非 ASCII 字符

Perl将文件句柄就地/流从cp1252转换为utf-8?

python - Pandas - 在数据框中找不到列

python - 将 NumPy 字符数组转换为字符串