python3编码

本文介绍了Python3中字符串的unicode编码特性,详细解释了如何使用decode将其他编码转换为unicode,以及如何使用encode将unicode转换为其他编码。此外,还提供了网络编程中解码和编码的实际应用案例。

python3内部是使用unicode编码的。字符串在Python3内部的表示是unicode编码,相当于python2的u''格式。

因此在编码解码时,可以先在Python内部使用decode解码为unicode,然后使用encode进行编码。

decode的作用是将其他编码的字符串转换成unicode编码,如str1.decode('gb2312'),表示将gb2312编码的字符串str1转换成unicode编码。 

encode的作用是将unicode编码转换成其他编码的字符串,如str2.encode('gb2312'),表示将unicode编码的字符串str2转换成gb2312编码。 (摘抄:https://blog.youkuaiyun.com/Amluee/article/details/78696047

 

在学网络编程中遇到的:

解码:

s = socket.socket()
s.bind((host, port))
s.listen(5)
connection, address = s.accept()
request = connection.recv(1024)
print(request)
# b'GET / HTTP/1.1\r\nHost: localhost:2000\r\nConnection: keep-alive\r\ncontent-type:text/html;charset=UTF-8\r\n\r\n'
print(type(request))
# <class 'bytes'>
print(request.decode('utf-8'))
'''
GET / HTTP/1.1
Host: localhost:2000
Connection: keep-alive
content-type:text/html;charset=UTF-8

'''
# 这里 utf-8编码的bytes ---> unicode编码
# 通过decode解码,转码的时候要先搞明白str是什么编码,这里使用utf-8进行解码,我也不知道为什么是这个

编码:

def index(request):
    head = 'HTTP/1.1 200 OK\r\n'
    body = '<h1>Hello cc</h1>'
    response = head + '\r\n' + body
    # b'' 表示这是一个 bytes 对象
    # 使用encode进行编码
    # # 这里  unicode编码 ---> utf-8编码
    return response.encode(encoding='utf-8')


# 下面的就不用再encode了
def index(request):
    head = b'HTTP/1.1 200 OK\r\n'
    
    with open('templates/index.html','rb') as f:
        body = f.read()

    response = head + b'\r\n' + body
    return response
#如果返回的response .encode(encoding='utf-8'),
#那么会报错: 'bytes' object has no attribute 'encode'
    

 

要修改Python 3编码默认值为UTF-8,请按照以下步骤操作: 1. 打开终端或命令提示符窗口。 2. 输入以下命令: ``` echo "export PYTHONIOENCODING=utf-8" >> ~/.bashrc ``` 如果您使用的是Windows系统,请使用以下命令: ``` echo "set PYTHONIOENCODING=utf-8" >> %USERPROFILE%\AppData\Local\Programs\Python\Python3X\Scripts\activate.bat ``` 其中,X是您安装的Python版本号。 3. 重新启动终端或命令提示符窗口。 现在,Python 3编码默认值已经被设置为UTF-8。 ### 回答2: 在Python3中,UTF-8是默认的编码格式。但有时候,当使用不同的编码格式时,我们需要更改默认编码。下面是如何在Python3中修改默认编码为UTF-8。 在Python3中,可以通过以下步骤修改默认编码格式: 1. 使用sys库调用setdefaultencoding方法,将默认编码设置为UTF-8。 ``` import sys sys.setdefaultencoding(&#39;UTF-8&#39;) ``` 2. 但是,Python3中没有setdefaultencoding()方法,所以我们需要使用其他方法来修改默认编码。 ``` import locale #获取本地默认编码 print(locale.getpreferredencoding()) #修改本地默认编码 locale.setlocale(locale.LC_ALL, &#39;en_US.UTF-8&#39;) ``` 使用该方法的好处是可以在多种操作系统中保持一致,并且可以防止可能的问题。 在修改默认编码后,我们可以通过以下方式测试它是否已成功更改: ``` import sys print(sys.getdefaultencoding()) ``` 这应该打印出UTF-8作为默认编码格式。这意味着,从现在开始,无论何时使用Python3,UTF-8都将是默认的编码格式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值