python - 在 iso8859_1 和 utf-8 之间转换 Python 字符串

标签 python encoding utf-8

我正在尝试在 python 中做与下面的 java 代码相同的事情。

String decoded = new String("中".getBytes("ISO8859_1"), "UTF-8");
System.out.println(decoded);

输出是一个中文字符串“中”。

在Python中,我尝试了编码/解码/字节数组,但总是得到不可读的字符串。我认为我的问题是我不太了解java/python编码机制是如何工作的。我也无法从现有答案中找到解决方案。

#coding=utf-8

def p(s):
    print s + ' --  ' + str(type(s))

ch1 = 'ä¸-'
p(ch1)

chu1 = ch1.decode('ISO8859_1')
p(chu1.encode('utf-8'))

utf_8 = bytearray(chu1, 'utf-8')
p(utf_8)

p(utf_8.decode('utf-8').encode('utf-8'))

#utfstr = utf_8.decode('utf-8').decode('utf-8')
#p(utfstr)

p(ch1.decode('iso-8859-1').encode('utf8'))
ä¸- --  <type 'str'>
ä¸Â- --  <type 'str'>
ä¸Â- --  <type 'bytearray'>
ä¸Â- --  <type 'str'>
ä¸Â- --  <type 'str'>

Daniel Roseman 的回答非常接近。谢谢。但当谈到我的真实案例时:

    ch = 'masanori harigae ã\201®ã\203\221ã\203¼ã\202½ã\203\212ã\203«ä¼\232è-°å®¤'
    print ch.decode('utf-8').encode('iso-8859-1')

我得到

回溯(最近一次调用最后一次): 文件“”,第 1 行,位于 文件“/apps/Python/lib/python2.7/encodings/utf_8.py”,第 16 行,解码 返回codecs.utf_8_decode(输入,错误,True) UnicodeDecodeError:“utf8”编解码器无法解码位置 19 中的字节 0x81:无效起始字节

Java代码:

    String decoded = new String("masanori harigae ã\201®ã\203\221ã\203¼ã\202½ã\203\212ã\203«ä¼\232è-°å®¤".getBytes("ISO8859_1"), "UTF-8");
    System.out.println(decoded);

输出为 Masanori harigae のパーソナル会�-�室

最佳答案

你的做法是错误的。您有一个错误编码为 utf-8 的字节串,并且您希望将其解释为 iso-8859-1:

>>> ch = "中"
>>> print u.decode('utf-8').encode('iso-8859-1')
中

关于python - 在 iso8859_1 和 utf-8 之间转换 Python 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40889917/

相关文章:

python 如何知道子进程是否正在等待输入

java - 将字符串转换为 RTF 格式

c++ - 如何在VC++ MFC应用程序中使用UTF-8编码

python - 字符串编码器 - Python

python - 当 AJAX 在 Django 中保存(并重新填充)我的表单时,为什么我会收到 '

javascript - 如何在 JavaScript 中将字节数组存储到本地文件中?

python - 权限错误 13 Python 3.5.2

python - 如何在 python 中扩展 1D FFT 代码来计算图像(2D)的 FFT?

python 3.8.0 - 在新行上打印带有变量值的自记录表达式

java - 使用 byte[] 和 charset 的构造函数创建字符串对象