Skip to main content
 首页 » 编程设计

python之为什么 str.encode ('ascii' ) 不适用于这种情况

2025年05月04日10zhenyulu

In [1]: str='美' 
 
In [2]: str.encode('utf-8') 
Out[2]: b'\xe7\xbe\x8e' 
 
In [3]: str.encode('utf-16') 
Out[3]: b'\xff\xfe\x8e\x7f' 
 
In [4]: str.encode('ascii') 
--------------------------------------------------------------------------- 
UnicodeEncodeError                        Traceback (most recent call last) 
/Users/XXXuserXXXTemp/<ipython-input-4-c7b96e3e54a7> in <module>() 
----> 1 str.encode('ascii') 
 
UnicodeEncodeError: 'ascii' codec can't encode character '\u7f8e' in position 0: ordinal not in range(128) 

str 是中文/日文字符。

  • 为什么 ascii 不起作用?

  • 如何理解 Out[2] 和 Out[3],即它们到底是什么?

请您参考如下方法:

Why ascii does not work?

str='美' 不是 ASCII 字符,它在 ASCII 范围之外,因此不能表示为 ASCII 字符。

来自Unicode tutorial for python :

Encodings don’t have to handle every possible Unicode character, and most encodings don’t. For example, Python’s default encoding is the ‘ascii’ encoding. The rules for converting a Unicode string into the ASCII encoding are simple; for each code point:

  1. If the code point is < 128, each byte is the same as the value of the code point.

  2. If the code point is 128 or greater, the Unicode string can’t be represented in this encoding. (Python raises a UnicodeEncodeError exception in this case.)


how to understand Out[2] and Out[3], i.e. what they really are?

它们是字节串(不是字符串)。 Out[2] 是字节序列,表示 UTF-8 代码单元中的 美 代码点。符号 \xe7 表示具有十六进制值 e7 的字节。 Out[3] 是字节序列,表示 UTF-16 代码单元中的 美 代码点。

要了解字符、字节和代码单元之间的区别,请阅读 Unicode tutorial for python仔细而完整。对于相同 Material 的另一种相当不错的处理,请阅读 Joel Spolsky 的 The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) .你应该知道这么多,没有任何借口!