最近看了很多同事的代碼,遇到一些之前沒用過的python語句,積累起來吧。
1 擷取本地MAC地址:
import uuid
mac = uuid.uuid1().hex[-12:]
2 del 的使用
a = ['b','c','d']
del a[0]
則a = ['c','d']
del a[0:1]
則a = ['d']
del a
則a未定義
3 a = ['c',''d]
a.reverse()
a = ['d','c']
b = ','.join(a)
b = 'd,c'
4 import random
x = random.randint(1,100)
y = random.choice( 'ABCD')
5 a=[1,2,3]
b=['a','b','c']
c=dict(zip(a,b))
則c = {1:'a',2:'b',3:'c'}
6 a='1-2-3-4'
b=map(int,a.split('-'))
則b = [1,2,3,4]
7 [] 使用
[].remove( value )
[].pop( index ) = value
[].count( x ) = x在列表中數量
{}使用
{}.pop( key ) = value
{}.get( key ) = value or {}.get( key ,0 ) 設預設值
8 a = str.decode( 'utf-8' )
b = str.encode( 'utf-8' )
str.isdigit() 是否數值
str1 = 'abc%s'%str2
9 import string
x= string.ascii_lowercase
則 x = 'abcdefghijklmnopqrstuvwxyz'
d = enumerate( x )
c = list( d )
則c = [(0,'a'),(1,'b').......]
for i ,j in d:
則i = 0,1,2,.....
j = 'a','b'......
10 a = test()[0]
當test()返回結果的長度為1時,上面語句等價於
a, = test()