Python3中的字符串与字节序列
python3中字符串只有一种就是str
- 不可变的序列
- 保存的是Unicode码位;
在Python3中,所有用单引号(’)、双引号(")、三引号(’’’、""")包围的都是str数据类型;
'这些在Python3中都是字符串'
"保存的都是Unicode文本"
'''
文体块1
'''
"""
文体块2
"""
Python3中的字节串有两种
- 不可变的bytes类型
- 可变的bytearray类型
只能用保存字节; 0 <= x < 256;
b1 = b'this is a bytes'
# b'this is a bytes'
ba1 = bytearray(b1) # bytearray(b'this is a bytes')
b2 = bytes('这是一个字节串',encoding='utf-8')
# b'\xe8\xbf\x99\xe6\x98\xaf\xe4\xb8\x80\xe4\xb8\xaa\xe5\xad\x97\xe8\x8a\x82\xe4\xb8\xb2'
s1 = 'abcde' # 字符串类型,Unicode编码
b1 = b'abcde' # 字节串类型,ASCII编码
list(s1) # ['a', 'b', 'c', 'd', 'e']
list(b1) # [97, 98, 99, 100, 101]
字符串的编码解码
Unicode字符串要保存在磁盘或在网络上传输要对其进行编码;
s1 = '这是一个Unicode字符串'
b1 = s1.encode(encoding='utf-8') # b1为bytes类型
# b'\xe8\xbf\x99\xe6\x98\xaf\xe4\xb8\x80\xe4\xb8\xaaUnicode\xe5\xad\x97\xe7\xac\xa6\xe4\xb8\xb2'
s2 = b1.decode(encoding='utf-8') # s2为str类型
# '这是一个Unicode字符串'
#下面的方式也可以
b1 = bytes(s1, encoding='utf-8')
s2 = str(b1, encoding='utf-8')
字符串拼接
'第一个串' + ' ' + '第二个串' # 1 '第一个串 第二个串'
' '.join(('第一个串','第二个串')) # 2
'{:s} {:s}'.format('第一个串','第二个串') # 3
'%s %s' % ('第一个串','第二个串') # 4
相对来说str.join()的方式更高效,但也不是绝对。