python之常用语法技巧

最近看了很多同事的代码,遇到一些之前没用过的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'......

你可能感兴趣的:(python)