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)
相关推荐
java1234_小锋33 分钟前
PyTorch2 Python深度学习 - transform预处理转换模块
开发语言·python·深度学习·pytorch2
景彡先生6 小时前
Python Selenium详解:从入门到实战,Web自动化的“瑞士军刀”
前端·python·selenium
珺毅同学8 小时前
YOLO输出COCO指标及YOLOv12报错
python·深度学习·yolo
2401_8414956410 小时前
Windows 系统中ffmpeg安装问题的彻底解决
windows·python·ffmpeg·bug·语音识别·下载·安装步骤
waysolong9010 小时前
MCP服务构建、使用
python
胜天半月子11 小时前
Python自动化测试 | 快速认识并了解pytest的基本使用
服务器·python·pytest
小小测试开发11 小时前
Python Web3库入门:从零开始与以太坊区块链交互
python·web3·区块链
独行soc11 小时前
2025年渗透测试面试题总结-224(题目+回答)
网络·python·安全·web安全·adb·渗透测试·安全狮
程序员三藏11 小时前
软件测试之环境搭建及测试流程
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例
10岁的博客11 小时前
PyTorch快速搭建CV模型实战
人工智能·pytorch·python