python学习之杂记
程序员文章站
2024-03-13 17:04:51
...
以下参考官方文档
0关于计算
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625 #交互式模式下,变量临时值赋给"_",so,可以利用"_"连续计算
>>> price + _
113.0625
>>> round(_, 2)
113.06
1字符串连接
>>> 'Py' 'thon' #与'Py'+'thon'等效
'Python'
2关于字符串
>>> word = 'Python'
#>>> word[0] = 'J'
# ...
#TypeError: 'str' object does not support item assignment
>>> 'J' + word[1:] #新建一个字符串
'Jython'
#>>> word[2:] = 'py'
# ...
#TypeError: 'str' object does not support item assignment
>>> word[:2] + 'py' #新建一个字符串
'Pypy'
3 other
>>> x = set ('spam')
>>> y = {'h','a','m'}
>>> x,y
({'s', 'm', 'a', 'p'}, {'h', 'm', 'a'})
>>> x & y
{'m', 'a'}
>>> x | y
{'s', 'm', 'p', 'h', 'a'}
>>> x - y
{'s', 'p'}
>>> {n**2 for n in [1,2,3,4]}
{16, 1, 4, 9}
>>> list(set([1,2,1,3,1,2,4,1]))
[1, 2, 3, 4]
>>> set('spam')-set('ham')
{'s', 'p'}
>>> set('spam')==set('maps')
True
>>> 'p' in set ('spam'),'p' in 'spam','ham' in ['eggs','spam','ham']
(True, True, True)
4 math
>>> import math
>>> math.floor(2.5)
2
>>> math.floor(-2.5)
-3
>>> math.trunc(2.5)
2
>>> math.trunc(-2.5) #这里有区别
-2
>>> 1j*1j
(-1+0j)
>>> 2+1j*3
(2+3j)
>>> (2+3j)*3
(6+9j)
>>> math.pi,math.e
(3.141592653589793, 2.718281828459045)
>>> math.sqrt(144),math.sqrt(2)
(12.0, 1.4142135623730951)
>>> min(1,2,3,4,5,-1,-2,-5),max(1,2,3,4,5,-1,-2,-5)
(-5, 5)
>>> sum((1,2,3,4,5))
15
5 Hex Octal Binary
>>> 0o1,0o10,0o377
(1, 8, 255)
>>> 0x01,0x10,0xff
(1, 16, 255)
>>> 0b1,0b10000,0b1111111
(1, 16, 127)
>>> 0xff,(15*(16**1)+(15*(16**0)))
(255, 255)
>>> 0x2f,(2*(16**1)+(15*(16**0)))
(47, 47)
>>> 0xf,0b1111,(1*(2**3)+1*(2**2)+1*(2**1)+1*(2**0))
(15, 15, 15)
>>> oct(64),hex(64),bin(64)
('0o100', '0x40', '0b1000000')
>>> 0o100,0x40,0b1000000,64
(64, 64, 64, 64)
6 Bitwise Operations
>>> x = 1 #0001
>>> x << 2 #0100
4
>>> x | 2
3
>>> x & 1
1
>>> x = 0b0001
>>> x << 2
4
>>> bin(x << 2)
'0b100'
>>> bin(x | 0b010)
'0b11'
>>> bin(x & 0b1)
'0b1'
上一篇: IPVS调度算法之WLC