1. 分片的步长,默认为值1,表示为 xx[s:t:v] ----从索引s到索引t,每隔v,取对应索引位置的值
xx = 'hello,world' #从索引0-10,共11个字符
xx[2:] #从索引2直到最后所有的值
Out[2]: 'llo,world'
xx[1:5:2] #从索引1到5,即xx[1:5]='ello',注意此时不含xx[5]的值,从xx[1]开始,每隔2取一个值,即取xx[1],xx[3]
Out[3]: 'el'
xx[::2] #对整个序列,此时序列包含末尾值,从xx[0]开始,每隔2取一个值,即取xx[0],xx[0+2],xx[2+2],xx[4+2],xx[6+2],xx[8+2]
Out[4]: 'hlowrd'
##注意:python索引是从0开始
2. 步长为负数时,有时候很有用,例如用于序列反转
##注意:python在负数索引时,序列的最后一位索引为-1,因此从右往左,依次是-1,-2,-3, ...
xx[::-1] #可以理解为先取整个序列,然后从索引0开始,依次取xx[0-1]也就是xx[-1],xx[-1-1]也就是xx[-2],xx[-3],...的值,也就是反转序列
Out[6]: 'dlrow,olleh'
xx[7:2:-1] #从索引7开始,每次-1,反转子序列,即xx[7],xx[6],...,但是同样不包含xx[2]的值
Out[7]: 'ow,ol'
3. 字符串转数字,数字转字符串
int('30') #'30'本身是一个字符串
Out[9]: 30
float('30')
Out[10]: 30.0
str(30)
Out[11]: '30'
4. 字符与ASCII码转化
ord('a') #ord函数获取字符的ASCII码值
Out[12]: 97
chr(97) #chr函数获取ASCII对应的字符
Out[13]: 'a'
5. 复数表示
2+-4j #一般用下面一种方法比较容易看,都可以得到复数2-4j
Out[14]: (2-4j)
2-4j
Out[15]: (2-4j)
6. 按位与、按位或
1 & 2 #二进制:0001 & 0010 = 0000
Out[18]: 0
1 & 1 # 0001 & 0001 = 0001
Out[19]: 1
1 | 2 # 0001 | 0010 = 0011
Out[21]: 3
7. 除法(/)与floor除法(//)
5/3 #直接除法
Out[16]: 1.6666666666666667
5//3 #floor除法结果,取小于1.66666666666666667的最大整数,也就是1
Out[17]: 1
5//-3 #取小于-1.66666666666666667的最大整数,也就是-2
Out[22]: -2
## 注:'%'对应数字时是取余数操作
8. math.floor和math.ceil函数
import math
math.floor(5/3) #同floor除法的解释
Out[25]: 1
math.floor(5/-3)
Out[28]: -2
math.ceil(5/3) #取大于1.666666666667的最小整数
Out[26]: 2
math.ceil(5/-3) #取大于-1.6666666666667的最小整数
Out[27]: -1
9. round 内置函数
round(1.8) #默认时,四舍五入均到个位,小数的话就会四舍五入取整了
Out[19]: 2
round(1.4) #默认时,四舍五入均到个位,小数的话就会四舍五入取整了
Out[22]: 1
round(1.345, 2) # 未进位
Out[79]: 1.34
round(1.145, 2) # 进位了,是不是很神奇。。。
Out[80]: 1.15
原因是:二进制转换造成的精度损失,导致round的时候出现这种情形
from decimal import Decimal #可用来查看保存的值
Decimal(1.345)
Out[65]: Decimal('1.3449999999999999733546474089962430298328399658203125') #此时求 round(1.345, 2)是不是得到的值就是1.34了
Decimal(1.145)
Out[66]: Decimal('1.145000000000000017763568394002504646778106689453125') #此时求 round(1.145, 2)是不是得到的值就是1.15了
如果确实想要一般的四舍五入的话,有很多其他的方法实现,例如:将为5的那一位加1之后再round。