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)
相关推荐
qq_17082750 CNC注塑机数采37 分钟前
【Python TensorFlow】 CNN-GRU卷积神经网络-门控循环神经网络时序预测算法(附代码)
python·rnn·机器学习·cnn·gru·tensorflow
云栈开源日记2 小时前
Python 开发技术栈梳理:从数据库、爬虫到 Django 与机器学习
数据库·爬虫·python·学习·机器学习·django
电子_咸鱼8 小时前
【STL string 全解析:接口详解、测试实战与模拟实现】
开发语言·c++·vscode·python·算法·leetcode
哈茶真的c8 小时前
【书籍心得】左耳听风:传奇程序员练级攻略
java·c语言·python·go
io_T_T9 小时前
Paddle-CLS图像分类_环境安装
python·日常软硬件经验分享
百***48079 小时前
Python使用PyMySQL操作MySQL完整指南
数据库·python·mysql
PNP Robotics10 小时前
PNP机器人上海宝山智能机器人年会发表机器人10年主题演讲演讲
人工智能·python·机器人
___波子 Pro Max.10 小时前
Python获取当前脚本目录路径
python
努力成为大牛吧10 小时前
Pycharm 接入 Deepseek API完整版教程
ide·python·pycharm
闲人编程10 小时前
Python对象模型:一切都是对象的设计哲学
开发语言·python·模型·对象·codecapsule·下划线