基础数据类型 -- 其他

 

布尔值

In [1]:
# True 和 False
 
布尔值与其他数据类型的转换
In [2]:
# 非空的数据结构都是True
# 非空字符串为True
# 非0数字为True
# None为False
 

空类型None

In [4]:
# 函数没有返回值返回None
 

字节码

In [5]:
# 在计算机内存中会统一使用unicode编码,然而当我们保存到硬盘或者需要传输的时候,
# 就转换为utf-8或者gbk等编码,一来节省了空间,二来也提高了传输效率。

# 在python3中,字符串是以unicode编码的,也就是说,python的字符串支持多种语言。

# 由于python中的字符串类型是str,在内存中以unicode表示,一个字符对应若干个字节。
# 如果要在网络上传输,或者保存到磁盘上,就需要把str变为以字节为单位的bytes(bytes使用
# utf-8,gbk或者其他编码方式)。
In [11]:
# Python对bytes类型的数据用带b前缀的单引号或双引号表示:
x = b'abc'
type(x)
Out[11]:
bytes
In [12]:
# 以unicode表示的str通过encode()方法可以编码为指定的bytes
s = "abcd"
print(s.encode("utf-8"))
print(s.encode("gbk"))
 
b'abcd'
b'abcd'
In [13]:
# 纯英文的str编码为bytes内容是一样的
# 无法显示为ASCII字符的字节,用\x##显示(十六进制)
# 一个\x##代表一个字节(8个二进制位)
s2 = "是我"
print(s2.encode("utf-8")) # utf-8用三个字节代表一个汉字
print(s2.encode("gbk")) # gbk用两个字节代表一个汉字
 
b'\xe6\x98\xaf\xe6\x88\x91'
b'\xca\xc7\xce\xd2'
In [14]:
# bytes类型decode()解码成字符串,encodeing指定解码方式
print(s2.encode("utf-8").decode("utf-8"))
print(s2.encode("gbk").decode("gbk"))
print(s2.encode("gbk").decode("utf-8")) # 无法解码
 
是我
是我
 
---------------------------------------------------------------------------
UnicodeDecodeError                        Traceback (most recent call last)
<ipython-input-14-afef9a2a407c> in <module>()
      2 print(s2.encode("utf-8").decode("utf-8"))
      3 print(s2.encode("gbk").decode("gbk"))
----> 4print(s2.encode("gbk").decode("utf-8"))

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xca in position 0: invalid continuation byte
 

还可以通过数据类型来转换

In [20]:
bytes("微微",encoding="utf-8")#用utf-8的形式转码成字节
Out[20]:
b'\xe5\xbe\xae\xe5\xbe\xae'
In [23]:
str(b'\xe5\xbe\xae\xe5\xbe\xae',encoding="utf-8")
Out[23]:
'微微'
posted @ 2018-03-27 15:30  瓜田月夜  阅读(92)  评论(0)    收藏  举报