zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    Android框架种类
    ASP.NET MVC 入门系列教程
    Jquery相关总结
    使用EF To Linq执行类似sql的in语句
    C#通过执行sql语句的方式执行存储过程,得到输出参数
    C#通过webapi中转上传文件到文件服务器
    sql中去除重复的数据
    web打印
    NPOI导出数据,设置格式,锁定单元格
    Uncaught SyntaxError: Invalid or unexpected token
  • 原文地址:https://www.cnblogs.com/qiufengsuopo/p/7326871.html
Copyright © 2011-2022 走看看