首页 > 编程语言 > 详细

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

时间:2020-02-21 16:14:10      阅读:179      评论:0      收藏:0      [点我收藏+]

直接上代码

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 
 4 """
 5 __title__  = 
 6 __Time__   = 2020/2/21 15:56
 7 
 8 """
 9 # bytes转字符串方式一
10 b = b\xe9\x80\x86\xe7\x81\xab
11 string = str(b, utf-8)
12 print(string)
13 
14 # bytes转字符串方式二
15 b = b\xe9\x80\x86\xe7\x81\xab
16 string = b.decode()  # 第一参数默认utf8,第二参数默认strict
17 print(string)
18 
19 # bytes转字符串方式三
20 b = b\xe9\x80\x86\xe7\x81haha\xab
21 string = b.decode(utf-8, ignore)  # 忽略非法字符,用strict会抛出异常
22 print(string)
23 
24 # bytes转字符串方式四
25 b = b\xe9\x80\x86\xe7\x81haha\xab
26 string = b.decode(utf-8, replace)  # 用?取代非法字符
27 print(string)
28 
29 # 字符串转bytes方式一
30 str1 = 逆火
31 b = bytes(str1, encoding=utf-8)
32 print(b)
33 
34 # 字符串转bytes方式二
35 b = str1.encode(utf-8)
36 print(b)

 

执行结果

逆火
逆火
逆haha
逆?haha?
b\xe9\x80\x86\xe7\x81\xab
b\xe9\x80\x86\xe7\x81\xab

 

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

原文:https://www.cnblogs.com/poloyy/p/12341746.html

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