首页 > 文章列表 > 中文在python中占几个字节

中文在python中占几个字节

Python 中文 字节
343 2022-08-07

如果是utf-8编码,那么一个中文字符占用三个字节,一个英文字符占用一个字节。如果是gbk编码,那么一个中文字符占用两个字节,一个英文字符占用一个字节。

如果是utf-8编码,那么一个中文包含繁体字等于三个字节,一个英文字符等于一个字节。

如果是gbk编码,那么一个中文包含繁体字等于两个字节,一个英文字符等于一个字节。

(推荐学习:Python入门教程)

我们可以用如下方法来判断:

中文和符号:

print(type('中文'.encode('utf-8')))  #输出为bytes类型
执行结果:
<class 'bytes'>

print(type('中文'.encode('gbk')))
执行结果:
<class 'bytes'>
print(len('中文'.encode('utf-8')))  #输出几个字节
执行结果:
6

print(len('中文'.encode('gbk')))
执行结果:
4

print(len(',。'.encode('gbk')))
执行结果:
4

英文字母和符号:

print(type('ab'.encode('utf-8')))
执行结果:
<class 'bytes'>
print(len('ab'.encode('utf-8')))
执行结果:
2

print(len(',.'.encode('gbk')))
执行结果:
2