本站改版新增arduino频道

Micropython
Arduino

micropython Python中bytes与字符串的相互转化


Python中bytes与字符串的相互转化

# bytes转字符串方式一

b=b'\xe9\x80\x86\xe7\x81\xab'

string=str(b,'utf-8')

print(string)

>>> 逆火

>>>

# bytes转字符串方式二

b=b'\xe9\x80\x86\xe7\x81\xab'

string=b.decode() # 第一参数默认utf8,第二参数默认strict

print(string)

>>> 逆火


# bytes转字符串方式三

b=b'\xe9\x80\x86\xe7\x81haha\xab'

string=b.decode('utf-8','ignore') # 忽略非法字符,用strict会抛出异常

print(string)

>>> 逆haha


# bytes转字符串方式四

b=b'\xe9\x80\x86\xe7\x81haha\xab'

string=b.decode('utf-8','replace') # 用?取代非法字符

print(string)

>>> 逆�haha�

>>>

# 字符串转bytes方式一

str1='逆火'

b=bytes(str1, encoding='utf-8')

print(b)

>>> b'\xe9\x80\x86\xe7\x81\xab'


# 字符串转bytes方式二

b=str1.encode('utf-8')

print(b)

>>> b'\xe9\x80\x86\xe7\x81\xab'



推荐分享
图文皆来源于网络,内容仅做公益性分享,版权归原作者所有,如有侵权请告知删除!
 

Copyright © 2014 ESP56.com All Rights Reserved
晋ICP备14006235号-22 晋公网安备14108102001165号

执行时间: 0.0097270011901855 seconds