天天看点

【Python】函数:bytes()、str()函数用法解析1 str->bytes2 bytes->str

(本文为原文章的部分转载,原文链接点这里)

1 str->bytes

>>> my_str = 'naruto1501144231'
>>> b_str1 = bytes(my_str, encoding='utf8') # 必须指定编码格式encoding
>>> b_str2 = my_str.encode('utf8') # # 字符串变量有encode方法
>>> print(my_str, type(my_str))
naruto1501144231 <class 'str'>
>>> print(b_str1, type(b_str1))
b'naruto1501144231' <class 'bytes'>
>>> print(b_str2, type(b_str2))
b'naruto1501144231' <class 'bytes'>
           

2 bytes->str

>>> b_str = b'xw150'
>>> my_str1 = str(b_str, encoding='utf8') # 必须指定解码方式encoding
>>> my_str2 = b_str.decode('utf8')
>>> print(b_str, type(b_str))
b'xw150' <class 'bytes'>
>>> print(my_str1, type(my_str1))
xw150 <class 'str'>
>>> print(my_str2, type(my_str2))
xw150 <class 'str'>
           

2.1 bytes函数详解

bytes函数返回一个新的bytes对象,该对象是一个0<=x<256区间内的整数不可变序列。

语法:

根据source的不同,最终得到的输出结果也不同:

2.1.1 source为整数:返回这个整数所指定长度的空字节数组

>>> b = bytes(8)
>>> print(b, len(b), type(b))
b'\x00\x00\x00\x00\x00\x00\x00\x00' 8 <class 'bytes'>

           

2.1.2 source为字符串:按照encoding将字符串转换为字节序列

>>> print(b, type(b))
b'NARUTO' <class 'bytes'>
           

2.1.3 source为可迭代类型:则source的元素必须为(0, 255]中的整数

>>> b = bytes([1,2,3])
>>> print(b, type(b))
b'\x01\x02\x03' <class 'bytes'
>>> c = bytes([1, 2, 256]) # 256不在(0,255]中,会报错
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: bytes must be in range(0, 256)
           

2.1.4 source没任何参数:初始化数组为0个元素

>>> b = bytes()
>>> print(b, type(b), len(b))
b'' <class 'bytes'> 0