从Unicode编码转为bytes

len()函数的使用

len()函数计算的是str的字符数,如果换成bytes,len()函数就计算字节数

可见,1个中文字符经过UTF-8编码后通常会占用3个字节,而1个英文字符只占用1个字节。

学习测试代码

"""
# -*- coding: utf-8 -*-
# @Time    : 2023/9/18 9:20
# @Author  : 王摇摆
# @FileName: Main.py
# @Software: PyCharm
# @Blog    :https://blog.csdn.net/weixin_44943389?type=blog
"""

# !/usr/bin/env python3
# -*- coding: utf-8 -*-

s = 'Python-中文'
print(s)

# 对字符串进行编码的转换
b = s.encode('utf-8')
print(b)
print(b.decode('utf-8'))

# 对len函数进行测试学习
print()

str1 = '你好'
str2 = str1.encode('utf-8')
print(str2)

print(type(str1))
print(type(str2))

print(len(str1))  # 如果是Unicode编码,就计算字符串的长度
print(len(str2))  # 如果是byte类型,就计算使用的字节的长度+



D:\ANACONDA\envs\pytorch\python.exe C:/Users/Administrator/Desktop/Code/Learn_Pyhon3.7/liaoxuefeng/Main.py
Python-中文
b'Python-\xe4\xb8\xad\xe6\x96\x87'
Python-中文

b'\xe4\xbd\xa0\xe5\xa5\xbd'
<class 'str'>
<class 'bytes'>
2
6

Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/weixin_44943389/article/details/132968964