python生成随机字符串

随机字符的场景大致有以下场景:

1.产生随机字符串 无数字

2.产生随机长度的字符串 无数字、有数字

3.产生随机手机号

4.产生随机n位的数字

5.产生随机n以内的数字

随机使用的两种思路如下:

一:使用random.randint(0,n)

我们有一个包含多个字符的数组(或称为数据源数组),想要生成一个特定长度的字符串。为了实现这一点,我们将编写一个程序,它会根据所需的字符串长度执行相应次数的循环。在每次循环中,程序会调用random.randint(0, n-1)函数来生成一个随机数,其中n是数据源数组的长度。这个随机数将被用作索引,从数据源数组中选择一个字符。然后,程序会将选出的字符添加到结果字符串中。循环结束后,程序将返回这个由随机字符拼接而成的字符串。

python 复制代码
def generate_random_str(randomlength=16):
  """
  生成一个指定长度的随机字符串
  """
  random_str =''
  base_str ='ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789'
  length =len(base_str) -1
  for i in range(randomlength):
    random_str +=base_str[random.randint(0, length)]
  return random_str
if __name__ == '__main__':
  print(generate_random_str(15))
二:使用random.choice来随机选择元素,如果需要生成一个长度为n的字符串,我们可以从给定的字符数据源中随机选择n次字符。

关于random.choice()的用法,该函数接受一个序列(如列表、元组或字符串)作为参数,并随机返回该序列中的一个元素。

以下是使用random.choice来实现所需功能的重新表述:

要生成一个由随机字符组成的字符串,其长度由变量n指定,我们可以从给定的字符数据源(比如一个包含所有可能字符的列表或字符串)中,使用random.choice()函数随机选择n个字符,并将这些字符连接起来。

例如,假设我们有一个字符列表作为数据源:

python 复制代码
import random  
  
# 假设的字符数据源  
characters = ['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']  
  
# 需要的字符串长度  
n = 10  
  
# 使用列表推导式和random.choice生成随机字符串  
random_string = ''.join(random.choice(characters) for _ in range(n))  
  
# 打印生成的随机字符串  
print(random_string)
python 复制代码
def getRandom(randomlength=16):
  """
  生成一个指定长度的随机字符串
  """
  digits=0123456789
  ascii_letters=abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
  str_list =[random.choice(digits +ascii_letters) for i in range(randomlength)]
  random_str =''.join(str_list)
  return random_str

最后,使用了dict字典实现按照mode按使用场景生成不同的字符串

python 复制代码
def getRandomString(mode="mixDigitLetter", len=15):
    #按照不同模式生成随机字符串
    upperLetter = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    lowerLetter = "abcdefghigklmnopqrstuvwxyz"
    digits="0123456789"
    wpecialCharacters = "!@#$%&_-.+="
    randomMap ={"digit":digits,"upper":upperLetter,"lower":lowerLetter,"mixDigitLetter":upperLetter+lowerLetter+digits,"mixLetter":upperLetter+lowerLetter,"mixDigitLetterCharcter":upperLetter+lowerLetter+digits+wpecialCharacters}
    return getRandom(randomMap[mode],len)
相关推荐
Juchecar14 小时前
解惑:NumPy 中 ndarray.ndim 到底是什么?
python
用户83562907805115 小时前
Python 删除 Excel 工作表中的空白行列
后端·python
Json_15 小时前
使用python-fastApi框架开发一个学校宿舍管理系统-前后端分离项目
后端·python·fastapi
数据智能老司机21 小时前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
数据智能老司机1 天前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机1 天前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机1 天前
精通 Python 设计模式——性能模式
python·设计模式·架构
c8i1 天前
drf初步梳理
python·django
每日AI新事件1 天前
python的异步函数
python
这里有鱼汤1 天前
miniQMT下载历史行情数据太慢怎么办?一招提速10倍!
前端·python