首页 > 编程语言 > 详细

python 中 str与bytes的转换

时间:2018-10-25 17:51:08      阅读:204      评论:0      收藏:0      [点我收藏+]
# 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)

# bytes转字符串方式四
b=b‘\xe9\x80\x86\xe7\x81haha\xab‘
string=b.decode(‘utf-8‘,‘replace‘) # 用?取代非法字符
print(string)

# 字符串转bytes方式一
str1=‘逆火‘
b=bytes(str1, encoding=‘utf-8‘)
print(b)

# 字符串转bytes方式二
b=str1.encode(‘utf-8‘)
print(b)

python 中 str与bytes的转换

原文:https://www.cnblogs.com/yingchen/p/9851270.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!