len()関数の使用
len() 関数は str の文字数を計算します。これがバイトに置き換えられた場合、len() 関数はバイト数を計算します。
通常、中国語の文字は UTF-8 エンコード後に 3 バイトを占有するのに対し、英語の文字は 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