我看到Python 手册 http://docs.python.org/2/library/stdtypes.html#string-methods提及.encode()
and .decode()
字符串方法。在 Python CLI 上运行我发现我可以创建 unicode 字符串u'hello'
具有与“常规”字符串不同的数据类型'hello'
并且可以转换/投射str()
。但当使用 ASCII 127 以上的字符时,真正的问题就开始了u'שלום'
我很难凭经验确定究竟发生了什么。
堆栈溢出 https://stackoverflow.com/questions/1207457/convert-unicode-to-string-in-python-containing-extra-symbols is https://stackoverflow.com/questions/2513027/encoding-gives-ascii-codec-cant-encode-character-ordinal-not-in-range128 溢出来 https://stackoverflow.com/questions/17026845/why-is-python-insisting-on-using-ascii with https://stackoverflow.com/questions/2365411/python-convert-unicode-to-ascii-without-errors examples https://stackoverflow.com/questions/6539881/python-converting-from-iso-8859-1-latin1-to-utf-8 of https://stackoverflow.com/questions/3224268/python-unicode-encode-error 困惑 https://stackoverflow.com/questions/2239017/how-do-i-properly-work-with-unicode-characters-in-python-to-keep-from-getting-er 关于 https://stackoverflow.com/questions/7634715/python-decoding-unicode-is-not-supported Python's https://stackoverflow.com/questions/8436522/noob-queries-on-unicode-and-str-methods-in-python unicode https://stackoverflow.com/questions/2596714/why-does-python-print-unicode-characters-when-the-default-encoding-is-ascii and https://stackoverflow.com/questions/985486/utf-8-problem-in-python-when-reading-chars 字符串编码/解码 https://stackoverflow.com/questions/6504200/how-to-decode-unicode-raw-literals-to-readable-string handling https://stackoverflow.com/questions/196345/how-to-check-if-a-string-in-python-is-in-ascii.
使用以下命令对字符串进行编码和解码时到底发生了什么(字节如何更改,数据类型如何更改)str()
方法,特别是当字符串中包含无法用7个字节表示的字符时?具有数据类型的 Python 变量是真的吗?<type 'str'>
可以同时编码和解码吗?如果它是编码的,我理解这意味着该字符串由 UTF-8、ISO-8859-1 或其他编码表示,这是正确的吗?如果解码了,这意味着什么?解码后的字符串是unicode吗?如果是这样,那么为什么他们没有数据类型<type 'unicode'>
?
为了以后阅读本文的人的利益,我认为 Python 2 和 Python 3 都应该得到解决。谢谢你!
这只是 Python 2 中的情况。decode
Python 2 字符串上的方法是一个疣,它在 Python 3 中已被更改(其中等效的,bytes
,只有decode
).
您无法对已经编码的字符串进行“编码”。当你打电话时会发生什么encode
on a str
是Python隐式调用decode
on it 使用默认编码,通常是 ASCII。这几乎总是不是您想要的。你应该经常打电话decode
在将 str 转换为不同的编码之前将其转换为 unicode。
(和解码的字符串are统一码,他们do有类型<unicode>
,所以我不知道你这个问题的意思。)
当然,在 Python 3 中,字符串默认是 unicode。您只能将它们编码为bytes
- 正如我上面提到的,它只能被解码。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)