1.相关基础
python3中有两种字符串类型:str
和bytes
python编码问题可以参考文章
str
以unicode
编码格式保存在内存
所以使用时,不用管前面要不要加u
(python2中需要考虑,不加u的话,在一些场合会报错)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
#!/usr/bin/python3 str0 = "i am fine thank you" print ( type (str0)) print (str0) str0 = u "i am fine thank you" print ( type (str0)) print (str0) # <class 'str'> # i am fine thank you # <class 'str'> # i am fine thank you |
定义byte类型时,在字符串前加b
1
2
3
4
5
6
7
8
|
#!/usr/bin/python3 str0 = b "i am fine thank you" print ( type (str0)) print (str0) # <class 'bytes'> # b'i am fine thank you' |
2.str和bytes相互转换
在文件传输过程中,通常使用bytes格式
的数据流,而代码中通常用str类型,因此str
和bytes
的相互转换就尤为重要。
2.1 bytes->str
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
#!/usr/bin/python3 bytes_data = b 'this is a message' print ( type (bytes_data)) print (bytes_data) # 方法一: str_data = str (bytes_data, encoding = 'utf-8' ) print ( type (str_data)) print (str_data) # 方法二: str_data = bytes_data.decode( 'utf-8' ) print ( type (str_data)) print (str_data) # <class 'bytes'> # b'this is a message' # <class 'str'> # this is a message # <class 'str'> # this is a message |
2.2 str->bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
#!/usr/bin/python3 str_data = 'this is a message' print ( type (str_data)) print (str_data) # 方法一: bytes_data = bytes(str_data, encoding = 'utf-8' ) print ( type (bytes_data)) print (bytes_data) # 方法二: bytes_data = str_data.encode( 'utf-8' ) print ( type (bytes_data)) print (bytes_data) # <class 'str'> # this is a message # <class 'bytes'> # b'this is a message' # <class 'bytes'> # b'this is a message' |
到此这篇关于python3 字符串str和bytes相互转换的文章就介绍到这了,更多相关python3 str与bytes内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/kids_budong_c/article/details/123672994?