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