Python字符和字节之间的相互转换

b = b"Hello, world!"  # bytes object  
s = "Hello, world!"   # str object 

print('str --> bytes')
print(bytes(s, encoding="utf8"))    
print(str.encode(s))   # 默认 encoding="utf-8"
print(s.encode())      # 默认 encoding="utf-8"

print('\nbytes --> str')
print(str(b, encoding="utf-8"))   
print(bytes.decode(b))  # 默认 encoding="utf-8"
print(b.decode())       # 默认 encoding="utf-8"
# bytes object 
b = b"example" 

# str object 
s = "example" 

# str to bytes 
bytes(s, encoding = "utf8") 

# bytes to str 
str(b, encoding = "utf-8") 

# an alternative method 
# str to bytes 
str.encode(s) 

# bytes to str 
bytes.decode(b)
encode
str to bytes 
decode
bytes to str
重要:ut-f8

猜你喜欢

转载自blog.csdn.net/qq_38361726/article/details/80086487
今日推荐