设计一个函数,生成一段由大小写英文字母(a-z , A-Z)和阿拉伯数字(0-9)组成的随机字符串。
如:
- 1aK3B5aL2
- 64akGIKA14a54
- KD123Hasd12Ad
随机字符串中,整体长度可以自己指定,但数字、大写字母、小写字母的长度和排列顺序要求是随机的。
下面的程序展现的时两种思想。
import random
# 方法一
def random_albt(count):
length = 0
while length < count:
select = random.choice(range(1, 4))
if select == 1:
a = random.choice(range(1, 10))
print(a, end="")
if select == 2:
b = random.choice(range(65, 90))
print(chr(b), end="")
if select == 3:
c = random.choice(range(97, 122))
print(chr(c), end="")
length += 1
# 方法二
def random_albt2(count):
s = list(map(lambda x: str(x), range(10))) + \
list(map(lambda x: chr(x), range(65, 90))) + \
list(map(lambda x: chr(x), range(97, 122)))
string = []
while count > 0:
current_len = random.randint(0, count)
string += random.sample(s, current_len)
count -= current_len
return "".join(string)
count = int(input("Please input the length you want:"))
#random_albt(count)
print(random_albt2(count))
其中,random.sample()可以从指定的序列中,随机的截取指定长度的片断,不作原地修改。
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 从list中随机获取5个元素,作为一个片断返回
slice = random.sample(list, 5)
print slice
# 原有序列并没有改变。
print list