python之生成随机数和字符串
Posted 知_行
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python之生成随机数和字符串相关的知识,希望对你有一定的参考价值。
最近看一个python的教学视频,视频里面有一个文本,一堆帐号,电话号码啥的,于是懒筋犯了,编辑假数据实在费劲,索性让这些数据自动生成
#coding:utf-8
import random
import sys
def stringList():
str1 = []
str3 = []
for i in range(97, 123):
str1.append(chr(i))
str2 = \'\'.join(str1)
for i in range(65, 91):
str3.append(chr(i))
str4 = \'\'.join(str3)
strall = str2 + str4
return strall
n = int(input("Please input u number :").strip())
\'\'\'
def idList():
x = 0
x += 1
return x
\'\'\'
def nameList():
a = random.randint(3,5)
name = \'\'.join(random.sample(stringList(), a))
return name
def dePartment():
list1 = [\'IT\', \'caiwu\', \'xiaoshou\']
dpt = random.choice(list1)
return dpt
def phoneList():
num = \'0123456789\'
phone = \'\'.join(random.choice(num) for i in range(11))
return phone
#把所有生成的数据写入到文件
listfile = open(\'memberlist.txt\', \'w\')
listfile.write(\'id name department phone\\n\')
listfile.close()
output = sys.stdout
with open(\'memberlist.txt\', \'a+\') as f:
sys.stdout = f
for i in range(0, n):
i += 1
print(\'%-5d %-8s %-13s %s\' % (i, nameList(), dePartment(), phoneList()))
sys.stdout = output
print(\'Wrote a total of %d rows of data\' % i)
输出结果如下
文件展示如下
END!
以上是关于python之生成随机数和字符串的主要内容,如果未能解决你的问题,请参考以下文章