Skip to main content
 首页 » 编程设计

python之在 Python 3 中从 utf-16 转换为 utf-8

2025年05月04日20lori

我正在使用 Python 3 编程,但遇到了一个小问题,我在网上找不到任何关于它的引用资料。

据我了解默认字符串是 utf-16,但我必须使用 utf-8,我找不到将从默认字符串转换为 utf-8 的命令。 非常感谢你的帮助。

请您参考如下方法:

在 Python 3 中,有两种不同的数据类型在您处理字符串操作时很重要。首先是字符串类,一个表示 unicode 代码点的对象。重要的是这个字符串不是一些字节,而是一个字符序列。其次,是字节类,它只是一个字节序列,通常表示以某种编码(如 utf-8 或 iso-8859-15)存储的字符串。

这对您意味着什么?据我了解,您想读写 utf-8 文件。让我们制作一个程序,用“ç”字符替换所有“ć”

def main(): 
    # Let's first open an output file. See how we give an encoding to let python know, that when we print something to the file, it should be encoded as utf-8 
    with open('output_file', 'w', encoding='utf-8') as out_file: 
        # read every line. We give open() the encoding so it will return a Unicode string.  
        for line in open('input_file', encoding='utf-8'): 
            #Replace the characters we want. When you define a string in python it also is automatically a unicode string. No worries about encoding there. Because we opened the file with the utf-8 encoding, the print statement will encode the whole string to utf-8. 
            print(line.replace('ć', 'ç'), out_file) 

那么什么时候应该使用字节?不经常。我能想到的一个例子是当您从套接字读取内容时。如果你在字节对象中有这个,你可以通过执行 bytes.decode('encoding') 将它变成一个 unicode 字符串,反之亦然使用 str.encode('encoding')。但如前所述,您可能不需要它。

仍然,因为它很有趣,这里是困难的方法,您自己对所有内容进行编码:

def main(): 
    # Open the file in binary mode. So we are going to write bytes to it instead of strings 
    with open('output_file', 'wb') as out_file: 
        # read every line. Again, we open it binary, so we get bytes  
        for line_bytes in open('input_file', 'rb'): 
            #Convert the bytes to a string 
            line_string = bytes.decode('utf-8') 
            #Replace the characters we want.  
            line_string = line_string.replace('ć', 'ç') 
            #Make a bytes to print 
            out_bytes = line_string.encode('utf-8') 
            #Print the bytes 
            print(out_bytes, out_file) 

关于这个主题(字符串编码)的好读物是 http://www.joelonsoftware.com/articles/Unicode.html .强烈推荐阅读!

来源:http://docs.python.org/release/3.0.1/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit

(P.S. 如你所见,我在这篇文章中没有提到 utf-16。我实际上不知道 python 是否使用它作为内部解码,但这完全无关紧要。目前你正在使用一个字符串,您使用的是字符(代码点),而不是字节。