1. 字符串与字节转换
a = b"Hello, world!" # bytes object
b = "Hello, world!" # str object
字符串转字节 str --> bytes
# 字符串转字节 str --> bytes
print(str.encode(b)) # 默认 encoding="utf-8"
print(bytes(b, encoding="utf8"))
print(b.encode()) # 默认 encoding="utf-8"
字节转字符串 bytes --> str
# 字节转字符串 bytes --> str
print(bytes.decode(a)) # 默认encoding="utf-8"
print(str(a, encoding="utf-8"))
print(a.decode()) # 默认 encoding="utf-8"
2. 拼接和分割
#字符拼接
b1 = bytes("hello", 'utf-8')
b2 = bytes('world', 'utf-8')
flag = bytes(' ', 'utf-8')
b3 = b1 + flag + b2
print(type(b3))
print(b3)
#字符分割
b4 = b3.split(b' ',1)
print(b4)
b5,b6 = b3.split(b' ')
print(b5)
print(b6)
#字符转字符串
s = b3.decode()
print(type(s))
print(s)
#字符串拼接
s1 = ' ok'
s2 = s + s1
print(s2)
#字符串分割
s3 = s2.split(' ')
print(s3)
s4,s5,s6 = s2.split(' ',2)
print(s4)
print(s5)
print(s6)
结果:
<class 'bytes'>
b'hello world'
[b'hello', b'world']
b'hello'
b'world'
<class 'str'>
hello world
hello world ok
['hello', 'world', 'ok']
hello
world
ok