Python基础知识

2020-09-24  本文已影响0人  子鱼_谋
1. Python中Unicode字符串

如果需要在程序中用到中文字符,需要在第一行增加:# -*- coding: utf-8 -*-不然会出现乱码

2. Python中布尔类型
True and True   # ==> True
True and False   # ==> False
False and True   # ==> False
False and False   # ==> False
True or True   # ==> True
True or False   # ==> True
False or True   # ==> True
False or False   # ==> False
not True   # ==> False
not False   # ==> True

布尔运算在计算机中用来做条件判断,根据计算结果为True或者False,计算机可以自动执行不同的后续代码。

要解释上述结果,又涉及到 and 和 or 运算的一条重要法则:短路计算。

  1. 在计算 a and b 时,如果 a 是 False,则根据与运算法则,整个结果必定为 False,因此返回 a;如果 a 是 True,则整个计算结果必定取决与 b,因此返回 b。

  2. 在计算 a or b 时,如果 a 是 True,则根据或运算法则,整个计算结果必定为 True,因此返回 a;如果 a 是 False,则整个计算结果必定取决于 b,因此返回 b。

所以Python解释器在做布尔运算时,只要能提前确定计算结果,它就不会往后算了,直接返回结果。

3. Python中raw字符串与多行字符串

如果一个字符串包含很多需要转义的字符,对每一个字符都进行转义会很麻烦。为了避免这种情况,我们可以在字符串前面加个前缀 r ,表示这是一个 raw 字符串,里面的字符就不需要转义了。例如:

r'\(~_~)/ \(~_~)/'

但是r'...'表示法不能表示多行字符串,也不能表示包含'和 "的字符串(为什么?)
如果要表示多行字符串,可以用'''...'''表示:

'''Line 1
Line 2
Line 3'''

上面这个字符串的表示方法和下面的是完全一样的:

'Line 1\nLine 2\nLine 3'

还可以在多行字符串前面添加 r ,把这个多行字符串也变成一个raw字符串:

r'''Python is created by "Guido".
It is free and easy to learn.
Let's start learn Python in imooc!'''
4. 格式化字符串
name = "python"
print("name is {0}, length = {1}".format(name, len(name)))
print("name is %s, length = %ld" % (name, len(name)))
print("name " * 5)
name name name name name
上一篇 下一篇

猜你喜欢

热点阅读