小Q:中庭地白树栖鸦,冷露无声湿桂花;今夜月明人尽望,不知秋思落谁家? 王建《十五夜望月》
两个密码生成代码实例
=============================================================
#!/usr/bin/python
#-*- coding:utf8 -*-
from random import randrange, sample
password_list = ['z','y','x','w','v','u','t','s','r','q','p','o','n','m','l','k','j','i','h','g','f','e','d','c','b','a',
'0','1','2','3','4','5','6','7','8','9',
'!','@','#','$','%','^','&','*','(',')','_','+','-','=',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
]
leng=15
password = "".join(sample(password_list, leng)).replace(' ', '')
print(password)
import…… #导入模块里所有属性或方法。
from……import #针对性的导入,也就是说导入模块里你想导入的属性或方法。
import os #导入os模块里所有的属性和方法
from random import randint #从random模块里仅仅导入 randint方法。
Python replace()方法
str.replace(old, new[, max])
#!/usr/bin/python
str = "this is string example....wow!!! this is really string";
print str.replace("is", "was");
print str.replace("is", "was", 3);
>>>>>>>>
thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string
join()函数
'sep'.join(seq)
参数说明
sep:分隔符。可以为空
seq:要连接的元素序列、字符串、元组、字典
上面的语法即:以sep作为分隔符,将seq所有的元素合并成一个新的字符串
返回值:返回一个以分隔符sep连接各个元素后生成的字符串
#########对序列进行操作(分别使用' '与':'作为分隔符)
>>> seq1 = ['hello','good','boy','doiido']
>>> print ' '.join(seq1)
hello good boy doiido
>>> print ':'.join(seq1)
hello:good:boy:doiido
#########对字符串进行操作
>>> seq2 = "hello good boy doiido"
>>> print ':'.join(seq2)
h:e:l:l:o: :g:o:o:d: :b:o:y: :d:o:i:i:d:o
##########对元组进行操作
>>> seq3 = ('hello','good','boy','doiido')
>>> print ':'.join(seq3)
hello:good:boy:doiido
##########对字典进行操作
>>> seq4 = {'hello':1,'good':2,'boy':3,'doiido':4}
>>> print ':'.join(seq4)
boy:good:doiido:hello
os.path.join()函数
语法: os.path.join(path1[,path2[,......]])
返回值:将多个路径组合后返回
注:第一个绝对路径之前的参数将被忽略
#############合并目录
>>> import os
>>> os.path.join('/hello/','good/boy/','doiido')
'/hello/good/boy/doiido'
random模块重要函数
1 )、random() 返回0<=n<1之间的随机实数n;
2 )、choice(seq) 从序列seq中返回随机的元素;
3 )、getrandbits(n) 以长整型形式返回n个随机位;
4 )、shuffle(seq[, random]) 原地指定seq序列;
5 )、sample(seq, n) 从序列seq中选择n个随机且独立的元素;
=============================================================
import string,random
length=8
seedlower=string.lowercase
seeddigit=string.digits
seedupper=string.uppercase
pwd=pwdd=pwdl=pwdu=''
countl=random.randrange(1,length-1)
countu=random.randrange(1,length-countl)
countd=(length-countl-countu)
#生成随机的字符
for l in random.sample(seedlower,countl):
pwdl+=l
for u in random.sample(seedupper,countu):
pwdu+=u
for d in random.sample(seeddigit,countd):
pwdd+=d
#在随机位置出现随机的字符
seed=pwdl+pwdu+pwdd
shuffler=random.sample(seed,len(seed))
pwd="".join(shuffler)
print pwd
String模块中的常量:
string.digits:数字0~9
string.letters:所有字母(大小写)
string.lowercase:所有小写字母
string.printable:可打印字符的字符串
string.punctuation:所有标点
string.uppercase:所有大写字母