Python-实现随机生成指定数量字符串的函数(方法)-记面试问题2

问题解析:函数有一参数x,函数需返回数量为x的随机字符的字符串

思路:笨办法,列出所有可能的字符作为操作对象(字符串,代码里面的方法func暂时只包含英文小写),或者对应的ASCII码值(32~126),然后用for循环执行x次每次随机生成1个字符,用join()方法连接起来返回字符串,或者不用for循环,只用random.sample()方法

 1 import random
 2 import string
 3 
 4 def func(a):
 5     str = 'abcedfghijklmnopqrstuvwxyz'
 6     list = []
 7     for i in range(0,a):
 8         list.append(str[random.randint(0,len(str)-1)])
 9     return ''.join(list)
10 print func(4)
11 #random.randint()函数返回的是制定范围内的随机整型数,str[]取得是字符串(数组)内的字符,''.join()是将list重新拼接成字符串
#join()连接的可以是元素序列、字符串、元组、字典,返回字符串
12 def func_choice(b): 13 list = [] 14 for i in range(0,b): 15 list.append(random.choice(string.ascii_lowercase)) 16 return ''.join(list) 17 print func_choice(5) 18 #random.choice()返回的是某一类型中的随机单个值,可以是字符串 19 def func_choice2(c): 20 list = [] 21 for i in range(0,c): 22 list.append(random.choice(string.letters)) 23 return ''.join(list) 24 print func_choice2(5) 25 26 def func_sample(d): 27 return ''.join(random.sample(string.letters,d)) 28 print func_sample(6) 29 #random.sample()随机返回固定长度的某一类型值 30 def func_num(e): 31 return ''.join(chr(random.randint(33,127)) for i in range(0,e)) 32 print func_num(18)

 

转载于:https://www.cnblogs.com/qiufengsuopo/p/7326871.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值