python 小知识总结汇整

一、=、==、is、id()

1、=(赋值)

a = 'yang'
print(a)
>>> yang

2、==(比较值是否相等)

a = 'yang'
b = 'yang'
print(a == b)
>>> True

3、is(比较内存地址是否相等)

a = 666
b = 666
print(a is b)
>>> False

4、id(内存地址)

a = 666
b = 888
print(id(a))
print(id(b))

>>> 6049680
>>> 10522416

二、小数字池

  1. 数字,字符串 小数据池

    • 数字的范围 -5 – 256
  2. 字符串:

  3. (1).不能有特殊字符
      (2).s*20 还是同一个地址,s*21以后都是两个地址

三、python3 编码

1、知识回顾

ascii
            A : 00000010  8位 一个字节

unicode     A : 00000000 00000001 00000010 00000100 32位  四个字节
            中:00000000 00000001 00000010 00000110 32位  四个字节


utf-8      A :  00100000 8位 一个字节
          中 :  00000001 00000010 00000110 24位 三个字节


gbk        A : 00000110  8位 一个字节
         中  : 00000010 00000110 16位 两个字节

1、各个编码之间的二进制,是不能互相识别的,会产生乱码。

2、文件的储存,传输,不能是unicode(只能是utf-8 utf-16 gbk,gb2312,asciid等)

2、python3中的编码

(1).string类型在内存中是用Unicode编码

(2).bytes类型:

英文:
str 
    表现形式: s = 'yang'
    编码方式:unicode
bytes
    表现形式:b'yang'
    编码方式:除unicode外的其他编码

中文:
str 
    表现形式: s = '中国'
    编码方式:unicode 
bytes
    表现形式:b'xe4xb8xadxe5x9bxbd'
    编码方式:除unicode外的其他编码

3、python3种str类型与bytes类型的互相转换

① str ——>bytes

# encode()方法,编码

s = 'yang'
print(s,type(s))
print(s.encode('utf-8'),type(s.encode('utf-8')))

>>> yang <class 'str'>
>>> b'yang' <class 'bytes'>

# -------------------------------------------------
c = '中国'
print(c,type(c))
print(c.encode('utf-8'),type(c.encode('utf-8')))

>>> 中国 <class 'str'>
>>> b'xe4xb8xadxe5x9bxbd' <class 'bytes'>

① bytes ——>str

# decode()方法,解码

s = b'yang'
print(s,type(s))
print(s.decode('utf-8'),type(s.decode('utf-8')))

>>> b'yang' <class 'bytes'>
>>> yang <class 'str'>

# -------------------------------------------------
c = b'xe4xb8xadxe5x9bxbd'
print(c,type(c))
print(c.decode('utf-8'),type(c.decode('utf-8')))

>>> b'xe4xb8xadxe5x9bxbd' <class 'bytes'>
>>> 中国 <class 'str'>
原文地址:https://www.cnblogs.com/lidaxu/p/8082063.html