万恶之源-再谈编码 本节主要内容:
- is和==的区别 3. 编码的问题
A Python program is constructed from code blocks. A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition. Each command typed interactively is a block. A script file (a file given as standard input to the interpreter or specified as a command line argument to the interpreter) is a code block. A script command (a command specified on the interpreter command line with the ‘-c‘ option) is a code block. The string argument passed to the built-in functions eval() and exec() is a code block.
A code block is executed in an execution frame. A frame contains some administrative information (used for debugging) and determines where and how execution continues after the code block’s execution has completed.
粗略的翻译:
什么是命令行?
- is和==
s = 'alex'
print(id(s)) # 4326667072
整数, 字符串串, 布尔值
The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object. So it should be possible to change the value of 1. I suspect the behaviour of Python in this case is undefined.
对于字符串串:
Incomputer science, string interning is a method of storing only onecopy of each distinct string value, which must be immutable. Interning strings makes some stringprocessing tasks more time- or space-efficient at the cost of requiring moretime when the string is created or interned. The distinct
- 指定驻留留.我们可以通过sys模块中的intern()函数来指定要驻留留的内容.
a = 1000
b = 1000
print(a is b)
三. 编码的补充
- encoding:utf-8 --
综上, 除了了ASCII码以外, 其他信息不能直接转换.
bytes的表现形式:
s = "alex"
print(s.encode("utf-8")) # 将字符串串编码成UTF-8 print(s.encode("GBK")) # 将字符串串编码成GBK
结果:
b'alex'
b'alex'
s = "中"
结果: b'\xe4\xb8\xad' b'\xd6\xd0'
编码和解码的时候都需要制定编码格式.
s = "我叫李李嘉诚"
print(s.encode("utf-8")) # b'\xe6\x88\x91\xe5\x8f\xab\xe6\x9d\x8e\xe5\x98\x89\xe8\xaf\x9a'
print(b'\xe6\x88\x91\xe5\x8f\xab\xe6\x9d\x8e\xe5\x98\x89\xe8\xaf\x9a'.decod e("utf-8")) # 解码
s = bs.decode("GBK") # 解码
bss = s.encode("UTF-8") # 重新编码
print(bss)